简体   繁体   中英

Python Merging Dataframes using multiple Columns

I have 2 dataframes that l need to merge intersecting multiple columns. I'm not getting the results l need as the resulting dataframe has mismatched dates.

数据框1

数据框2

I want to merge a pair of columns Date & Segment from dataframe1 to (tmcN & date) | (tmcP & date) from dataframe2 as common columns. Specifically column Segment will match either tmcN or tmcP while at the same time the Date column will be matched to date. I've tried several different ways and can't configure it properly.

My Code:

left2 = Speed.rename({'key':'Segment'}, axis=1)
right2 = Incident.rename({'key':'tmcN'}, axis=1)

Test = left2.merge(right2, left_on='Segment', right_on='tmcN', how='outer')

This only matches Segment to tmcN and my laptop crashes when trying to double merge Segment to tmcP. Thank you for the assistance.

结果错误

You could try this ( assuming that df1 is the first dataframe and df2 is the second dataframe )

  1. Using tmcN of the second dataframe

     df = pd.merge(df1, df2, left_on=['Date', 'Segment'], right_on=['date', 'tmcN'])
  2. Using tmcP of the second dataframe

     df = pd.merge(df1, df2, left_on=['Date', 'Segment'], right_on=['date', 'tmcP'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM