Adam Schroeder
Adam Schroeder

Reputation: 768

merging dataframes on the same index

I can't find the answer to this in here. I have two dataframes:

index,  name,   color, day
   0    Nan     Nan    Nan
   1    b       red    thu
   2    Nan     Nan    Nan
   3    d       green  mon

index,  name,  color,   week
    0    c      blue    1
    1    Nan    Nan     Nan
    2    t      yellow  4
    3    Nan    Nan     Nan

And I'd like the result to be one dataframe:

index,  name,   color,  day,   week  
    0       c   Blue    Nan    1
    1       b   red     thu    Nan
    2       t   yellow  Nan    4
    3       d   green   mon    Nan

Is there a way to merge the dataframes on their indexes, while adding new columns?

Upvotes: 1

Views: 526

Answers (1)

jezrael
jezrael

Reputation: 862406

You can use DataFrame.combine_first:

df = df1.combine_first(df2)
print (df)
    color  day name  week
0    blue  NaN    c   1.0
1     red  thu    b   NaN
2  yellow  NaN    t   4.0
3   green  mon    d   NaN

For custom order of columns create columns names by numpy.concatenate, pd.unique and then add reindex_axis:

cols = pd.unique(np.concatenate([df1.columns, df2.columns]))
df = df1.combine_first(df2).reindex_axis(cols, axis=1)
print (df)
  name   color  day  week
0    c    blue  NaN   1.0
1    b     red  thu   NaN
2    t  yellow  NaN   4.0
3    d   green  mon   NaN

EDIT:

Use rename columns:

df = df1.combine_first(df2.rename(columns={'week':'day'}))
print (df)
  name   color  day
0    c    blue    1
1    b     red  thu
2    t  yellow    4
3    d   green  mon

Upvotes: 2

Related Questions