Skip to content Skip to sidebar Skip to footer

Complex Dataframe Merge Python Pandas

I am trying to merge 2 dataframes and can't quite get what I'm looking for. Dataframe 1 looks like this. Index Date Data1 Data2 A 2007-07-21 76 32 A

Solution 1:

set_index + concat

pd.concat([df1.set_index(['Index','Date']),df2.set_index(['Index','Date'])],1).reset_index()
Out[1145]: 
  IndexDateData1Data2Data3Data40A2007-07-2176.032.0NaNNaN1A2007-07-24NaNNaN14.0NaN2A2007-08-13NaN23.067.051.03B2007-06-1553.0NaNNaNNaN4B2007-06-21NaNNaN32.036.05B2007-07-1587.039.0NaN91.0

Or we can use merge

df1.merge(df2,on=['Index','Date'],how='outer')
Out[1147]: 
  IndexDateData1Data2Data3Data40A2007-07-2176.032.0NaNNaN1A2007-08-13NaN23.067.051.02B2007-06-1553.0NaNNaNNaN3B2007-07-1587.039.0NaN91.04A2007-07-24NaNNaN14.0NaN5B2007-06-21NaNNaN32.036.0

Post a Comment for "Complex Dataframe Merge Python Pandas"