[英]How Do I match two Data Frames in Pandas with multiple matches?
I have 2 data frames I want to match some data from one data frame and append it on another.我有 2 个数据帧,我想将一个数据帧中的一些数据和 append 匹配到另一个数据帧上。
df1 looks like this: df1 看起来像这样:
sourceId来源 ID | firstName名 | lastName姓 |
---|---|---|
1234 1234 | John约翰 | Doe能源部 |
5678 5678 | Sally莎莉 | Green绿色的 |
9101 9101 | Chlodovech克洛多维奇 | Anderson安德森 |
df2 looks like this: df2 看起来像这样:
sourceId来源 ID | agentId代理 ID |
---|---|
123456789 123456789 | 1234,5678 1234,5678 |
987654321 987654321 | 9101 9101 |
143216546 143216546 | 1234,5678 1234,5678 |
I want my Final Data Frame to look like this:我希望我的最终数据框看起来像这样:
sourceId来源 ID | firstName名 | lastName姓 | agentId代理 ID |
---|---|---|---|
1234 1234 | John约翰 | Doe能源部 | 123456789,143216546 123456789,143216546 |
5678 5678 | Sally莎莉 | Green绿色的 | 123456789,143216546 123456789,143216546 |
9101 9101 | Chlodovech克洛多维奇 | Anderson安德森 | 987654321 987654321 |
Usually appending stuff is easy but I'm not quite sure how to match this data up, and then append the matches with commas in-between them.通常附加东西很容易,但我不太确定如何匹配这些数据,然后 append 匹配它们之间的逗号。 I'm fairly new to using pandas so any help is appreciated.我对使用 pandas 还很陌生,因此不胜感激。
This works.这行得通。 It's long and not the most elegant, but it works well:)它很长而且不是最优雅的,但效果很好:)
tmp = df2.assign(agentId=df2['agentId'].str.split(',')).explode('agentId').set_index('agentId')['sourceId'].astype(str).groupby(level=0).agg(list).str.join(',').reset_index()
df1['sourceId'] = df1['sourceId'].astype(str)
new_df = df1.merge(tmp, left_on='sourceId', right_on='agentId').drop('agentId',axis=1).rename({'sourceId_x':'sourceId', 'sourceId_y':'agentId'},axis=1)
Output: Output:
>>> new_df
sourceId firstName lastName agentId
0 1234 John Doe 123456789,143216546
1 5678 Sally Green 123456789,143216546
2 9101 Chlodovech Anderson 987654321
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.