Merge two dataframes with multi-index Merge two dataframes with multi-index pandas pandas

Merge two dataframes with multi-index


Option 1
Use pd.DataFrame.reindex + pd.DataFrame.join
reindex has a convenient level parameter that allows you to expand on the index levels not present.

df1.join(df2.reindex(df1.index, level=0))             A   B   C   D   E   Ffirst  one  a1  b1  c1  d1  e1  f1       two  a2  b2  c2  d1  e1  f1second one  a3  b3  c3  d2  e2  f2       two  a4  b4  c4  d2  e2  f2

Option 2
You can rename your axes and join will work

df1.rename_axis(['a', 'b']).join(df2.rename_axis('a'))             A   B   C   D   E   Fa      b                          first  one  a1  b1  c1  d1  e1  f1       two  a2  b2  c2  d1  e1  f1second one  a3  b3  c3  d2  e2  f2       two  a4  b4  c4  d2  e2  f2

You can follow that up with another rename_axis to get desired results

df1.rename_axis(['a', 'b']).join(df2.rename_axis('a')).rename_axis([None, None])             A   B   C   D   E   Ffirst  one  a1  b1  c1  d1  e1  f1       two  a2  b2  c2  d1  e1  f1second one  a3  b3  c3  d2  e2  f2       two  a4  b4  c4  d2  e2  f2