0

I have two pandas dataframes. df1 is indexed by a multi-index (name, date). df2 is a simple 0 to n index with a 'Date' column. My question is how I can merge these two dataframes by date, while keeping the multi-index.

I used following command to merge. The merged dataframe don't have the multi-index anymore.

 df_merg = pd.merge(df1, df2, how='left', left_on='date', righ_on='Date')
Lei Hao
  • 708
  • 1
  • 7
  • 21
  • Possible duplicate of [How to keep index when using pandas merge](https://stackoverflow.com/questions/11976503/how-to-keep-index-when-using-pandas-merge) –  Sep 27 '19 at 09:43

1 Answers1

0

One possible solution is to reset_index for df1 before merge and set_index for df_merg after merge

df1.reset_index(level=['name', 'date'], inplace=True)
df_merg = pd.merge(df1, df2, how='left', left_on='date', right_on='Date')
df_merg = df_merg.set_index(['name', 'date'])
henrywongkk
  • 1,840
  • 3
  • 17
  • 26