python - 根据与熊猫的部分匹配合并列
问题描述
我有 2 个 dfs,我想通过以下方式合并它们:
- 与 column 完全匹配X
。
- 中Y
和Z
中的数字pdf
应在 中的范围内odf
,即使只是部分。
#odf
X Y Z
b1 s1 3 19
b2 s1 5 300
b4 s3 500 550
b6 s5 5 25
#pdf
X Y Z
d3 s2 7 12 #wrong s
d6 s1 50 220 #match b2 above
d7 s3 503 509 #match b4 above
d16 s5 15 30 #accept match to b6, partial match in Y/Z.
d18 s5 4 15 #accept match to b6
在这种情况下,我会得到:
#iodf and ipdf are indices of the two dfs above
iodf X Yodf Zodf ipdf Ypdf Zpdf
b2 s1 5 300 d6 50 220
b4 s3 500 550 d7 503 509
b6 s5 5 25 d16 15 30
b6 s5 5 25 d18 4 15
我正在考虑在每个 df 中创建一个带有正则表达式的附加列,并根据该正则表达式合并它们。
odf.loc[:,'id']=odf.X+'\\_`+odf.Y.astype(str)+'\\_`+odf.Z.astype(str)
pdf.loc[:,'id']=pdf.X+'\\_`+pdf.Y.astype(str)+'\\_`+pdf.Z.astype(str)
问题是我需要指定Y
和Z
作为范围的值,但我不完全确定如何处理这一点。有什么建议么?提前非常感谢!
解决方案
IIUC,您可以执行以下操作:
df = odf.reset_index().merge(pdf.reset_index(), on='X', suffixes=('odf','pdf'))
cleaned = df[(df['Ypdf'].between(df['Yodf'], df['Zodf'])) | (df['Zpdf'].between(df['Yodf'], df['Zodf']))]
产量:
indexodf X Yodf Zodf indexpdf Ypdf Zpdf
1 b2 s1 5 300 d6 50 220
2 b4 s3 500 550 d7 503 509
3 b6 s5 5 25 d16 15 30
4 b6 s5 5 25 d18 4 15
推荐阅读
- python - 如何处理 SQLAlchemy、flask、pyhon 中的唯一数据
- php - 展开具有相同值 PHP SQL 的行
- android - 在 Android 的后台线程上初始化 Firebase 是否安全?需要注意什么?
- sql-server - 插入表并导入数据后如何创建列
- reactjs - 当数据来自服务器时如何使用反应选择
- http-headers - 来自 Nginx 反向代理服务器而不是客户端的 REMOTE_ADDR IP
- c# - 通过在 Visual Studio 中按“点”在运行时列出 ExpandoObject 属性
- asp.net - MVC 事件是否重叠?
- ember.js - 如何在不涉及路由的 setupController 的情况下将属性从一个控制器传递到另一个控制器?
- mysql - 根据客户购买的产品过滤客户