Home > Software engineering >  Merging 2 dataframes on index and columns
Merging 2 dataframes on index and columns

Time:11-24

I am really stuck on a merger/ join of 2 dataframes. I would like to merge both on index and columns, here is an example

df1 :

         A   B   C
index 1  0   a   b
index 2  a   0   c
index 3  b   c   0

df 2 :

         B   C   D
index 2  0   c   d
index 3  c   0   e
index 4  d   e   0

I would like to get :

df3:
         A   B   C   D
index 1  0   a   b   nan
index 2  a   0   c   d
index 3  b   c   0   e
index 4  nan d   e   0

I tried many combinations of merge, join, concat and can't find the solution, could you please help me??? Eternal gratitude!!

CodePudding user response:

It is not clear if you want a real merge, i.e. what should happen in case of a mismatch in the overlapping indices.

Assuming there is no mismatch, you can combine_first:

out = df1.combine_first(df2)

Output:

          A  B  C    D
index1    0  a  b  NaN
index2    a  0  c    d
index3    b  c  0    e
index4  NaN  d  e    0
  • Related