Search code examples
python-3.xxlsxxls

python: How to concat horizontally two xls file with one column each into one xls file with 2 columns


I have one file called input1.xls with one column and an another called input2.xls with one column. I want to get a file called output.xls with 2 columns and no index (I noticed that whether i set ignore_index to True or False i always get index in my output.xls file). If possible i want to insert a header(letter, number) in the output.xls file as shown below

input1.xls  input2.xls 
  
a           1
b           2
c           3
d           4

output.xls

letter   number
a           1
b           2
c           3
d           4

import pandas as pd

df1 = pd.read_csv('input1.xls')
df2 = pd.read_csv('input2.xls')

(pd.concat([df1, df2], axis=1, ignore_index=True).to_csv('out.xls'))

Solution

  • You can use df.columns, as follows:

    import pandas as pd
    
    df1 = pd.DataFrame({
        0: ['a', 'b', 'c', 'd']
    })
    
    df2 = pd.DataFrame({
        0: [1, 2, 3, 4]
    })
    
    output = pd.concat([df1, df2], axis=1, ignore_index=True)
    output.columns = ['letter', 'number']  # to add column names
    output.to_csv('out.xls', index=False)
    

    When I opened the file with MS Excel, it looks like:

    enter image description here