Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas merge DataFrames based on index/column combination

I have two DataFrames that I want to merge. I have read about merging on multiple columns, and preserving the index when merging. My problem needs to cater for both, and I am having difficulty figuring out the best way to do this.

The first DataFrame looks like this

enter image description here

and the second looks like this

enter image description here

I want to merge these based on the Date and the ID. In the first DataFrame the Date is the index and the ID is a column; in the second DataFrame both Date and ID are part of a MultiIndex.

Essentially, as a result I want a DataFrame that looks like DataFrame 2 with an additional column for the Events from DataFrame 1.

like image 772
Philip O'Brien Avatar asked Nov 09 '22 12:11

Philip O'Brien


1 Answers

I'd suggest reseting the index (reset_index) and then merging the DataFrame, as you've read. Then you can set the index (set_index) to reproduce your desired MultiIndex.

like image 85
DrTRD Avatar answered Nov 15 '22 13:11

DrTRD