[英]Matching two columns from Pandas Dataframe but the order matters
我有两个DataFrames
df_1 :
idx A X
0 1 A
1 2 B
2 3 C
3 4 D
4 1 E
5 2 F
和df_2 :
idx B Y
0 1 H
1 2 I
2 4 J
3 2 K
4 3 L
5 1 M
我的目标是得到以下结果: df_result :
idx A X B Y
0 1 A 1 H
1 2 B 2 I
2 4 D 4 J
3 2 F 2 K
我正在尝试根据df_2中的B
列来匹配A
和B
列。
A
列和B
列在达到 4 后重复其内容。这里的顺序很重要,因为 df_1 中idx = 4
的行与df_2中 idx = idx = 5
的行不匹配。
我试图使用:
matching = list(set(df_1["A"]) & set(df_2["B"]))
接着
df1_filt = df_1[df_1['A'].isin(matching)]
df2_filt = df_2[df_2['B'].isin(matching)]
但这没有考虑顺序。
我正在寻找一个没有很多 for 循环的解决方案。
编辑:
df_result = pd.merge_asof(left=df_1, right=df_2, left_on='idx', right_on='idx', left_by='A', right_by='B', direction='backward', tolerance=2).dropna().drop(labels='idx', axis='columns').reset_index(drop=True)
得到我想要的。
IIUC 这应该有效:
df_result = df_1.merge(df_2,
left_on=['idx', 'A'], right_on=['idx', 'B'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.