Louis
Louis

Reputation: 1305

merge columns with same header name

Let's say I have two dfs: df1=

index      colx      coly      colz
  0         45        35        54

df2=

index      colz      colx      colg      colf
  0         11        22        10         5

I want df1 to be:

index      colx      coly      colz      colf  
  0         45        35        54       nan
  1         22        nan       11        5

I was looking into merge and join, but I don't seem to be able to do it correctly

Thank you

Upvotes: 1

Views: 709

Answers (2)

rafaelc
rafaelc

Reputation: 59274

Using pd.concat

pd.concat([df, df2], sort=False)[df.set_index('index').columns].reset_index(drop=True)

    colx    coly    colz
0   45      35.0    54
1   22      NaN     11

Using pd.merge

pd.merge(df,df2, how='outer')[df.set_index('index').columns]

    colx    coly    colz
0   45      35.0    54
1   22      NaN     11

Upvotes: 0

DYZ
DYZ

Reputation: 57033

You can join the transposed dataframes, transpose the result again, and add a default numeric index:

df1.T.join(df2.T, rsuffix='r').T.reset_index(drop=True)
#       colx  coly  colz
#0      45.0  35.0  54.0
#1      22.0   NaN  11.0

Upvotes: 1

Related Questions