+1 vote
in Programming Languages by (40.5k points)

I want to concatenate two dataframes along axis=1, but the following code drops the column names and puts 0, 1, 2, 3...

How can I concatenate dataframes without losing column/header names?

pd.concat([df1,df2], axis=1, ignore_index=True)

1 Answer

+1 vote
by (351k points)
selected by
 
Best answer

The concat() function is dropping header names because you have used ignore_index=True.

You can either drop the parameter ignore_index or set ignore_index=False to retain the column names.

Here is an example:

>>> import pandas as pd

>>> df1 = pd.DataFrame({'a':[1,2,3,4,5,1,3], 'b':[11,12,13,14,15,12,16]})

>>> df2 = pd.DataFrame({'a':[1,2,3,4,5,1,3], 'b':[11,12,13,14,15,12,16]})

>>> pd.concat([df1,df2], axis=1, ignore_index=True)

   0   1  2   3

0  1  11  1  11

1  2  12  2  12

2  3  13  3  13

3  4  14  4  14

4  5  15  5  15

5  1  12  1  12

6  3  16  3  16

>>> pd.concat([df1,df2], axis=1, ignore_index=False)

   a   b  a   b

0  1  11  1  11

1  2  12  2  12

2  3  13  3  13

3  4  14  4  14

4  5  15  5  15

5  1  12  1  12

6  3  16  3  16

>>> pd.concat([df1,df2], axis=1)

   a   b  a   b

0  1  11  1  11

1  2  12  2  12

2  3  13  3  13

3  4  14  4  14

4  5  15  5  15

5  1  12  1  12

6  3  16  3  16

>>> 


...