mpg
mpg

Reputation: 3919

python pandas concat- reindex column labels

I have two dataframes that I want to concatenate column-wise together. They have no headers. So the first dataframe's columns are labeled 0-356. The second df is a single column and labeled 0.

DF1

    0  1   2  3 ..356
1   1   1  2  3   4
2   5   7  8  9   10
3   11  12 13 14  15

DF2

    0   
1   76
2   77
3   78

When I combine with concat

DF3=pd.concat([DF1, DF2],axis=1) 

I get two columns labeled 0

DF3

   0   0   1  2  3 ...356
1  76  1   1  2  3   4
2  77  5   7  8  9   10
3  78  11  12 13 14  15

Having two "0" columns obviously causes me problems later in the analysis.

How do you change or re index so my columns in DF3 would be labeled 0-357?

Upvotes: 1

Views: 2168

Answers (2)

JAB
JAB

Reputation: 12801

Rename the columns after the concat like so:

import numpy as np
import pandas as pd
df1 =pd.DataFrame(np.random.rand(3,1))
df2 =pd.DataFrame(np.random.rand(3,356))
df3 =pd.concat([df1,df2],axis=1)
df3.columns = range(357)

Upvotes: 0

EdChum
EdChum

Reputation: 394279

You need to pass ignore_index=True, this will reindex the rhs if there is a clash:

In [39]:

pd.concat([df,df1], axis=1, ignore_index=True)
Out[39]:
    0   1   2   3   4   5
1   1   1   2   3   4  76
2   5   7   8   9  10  77
3  11  12  13  14  15  78

Compare with the default which if you don't pass a param defaults to False:

In [40]:

pd.concat([df,df1], axis=1)
Out[40]:
    0   1   2   3   4   0
1   1   1   2   3   4  76
2   5   7   8   9  10  77
3  11  12  13  14  15  78

Upvotes: 3

Related Questions