首页 > 解决方案 > 根据与熊猫的部分匹配合并列

问题描述

我有 2 个 dfs,我想通过以下方式合并它们:
- 与 column 完全匹配X
- 中YZ中的数字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)

问题是我需要指定YZ作为范围的值,但我不完全确定如何处理这一点。有什么建议么?提前非常感谢!

标签: pythonregexpandas

解决方案


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

推荐阅读