python - 匹配 Pandas Dataframe 中的两列,但顺序很重要
问题描述
我有两个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中的列来匹配A
和列。B
B
列A
并B
在到达 4 后重复它们的内容。这里的顺序很重要,因为 df_1 中的行与df_2中的行idx = 4
不匹配。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'])
推荐阅读
- c# - 模型可以直接与数据访问层通信吗?
- typo3 - 如何提供自定义 FE-Authentification 方法
- php - PHP 将 MS SQL 输出到可下载的 CSV 或 Excel 文件
- javascript - 两个组件之间切换的vue过渡动画不流畅
- tomcat - 如何更改 Tomcat 8.5 日志文件夹
- java - 错误:在类路径上找到多个 RestConsumerFactory
- php - 如何将信息从表格复制到 PHP?
- reactjs - (反应)只渲染一个孩子(来自props.children)取决于路线(location.pathname)
- woocommerce - 隐藏除 Woocommerce 产品页面之外的所有 Wordpress 元素?
- sql - SQL Group By 和 Sum 帮助