使用difflib SequenceMatcher比率在Pandas中合并

时间:2015-07-30 21:36:00

标签: python merge fuzzy-search difflib

我试图弄清楚是否有基于difflib SequenceMatcher配置在Pandas中进行字符串模糊合并的方法。基本上,我有两个看起来像这样的数据框:

df_a
company    address        merged
Apple     PO Box 3435       1

df_b
company     address
Apple Inc   PO Box 343

我想像这样合并:

df_c = pd.merge(df_a, df_b, how = 'left', on = (difflib.SequenceMatcher(None, df_a['company'], df_b['company']).ratio() > .6) and (difflib.SequenceMatcher(None, df_a['address'], df_b['address']).ratio() > .6)

有一些帖子与我正在寻找的内容很接近,但它们都不适用于我想做的事情。 关于如何使用difflib进行这种模糊合并的任何建议?

1 个答案:

答案 0 :(得分:1)

可能有用的东西:测试列值的所有组合的部分匹配。如果匹配,则为df_b分配一个键以进行合并

df_a['merge_comp'] = df_a['company'] # we will use these as the merge keys
df_a['merge_addr'] = df_a['address']

for comp_a, addr_a in df_a[['company','address']].values:
    for ixb, (comp_b, addr_b) in enumerate(df_b[['company','address']].values)
        if difflib.SequenceMatcher(None,comp_a,comp_b).ratio() > .6:
            df_b.ix[ixb,'merge_comp'] = comp_a # creates a merge key in df_b
        if difflib.SequenceMatcher(None,addr_a, addr_b).ratio() > .6:
            df_b.ix[ixb,'merge_addr'] = addr_a # creates a merge key in df_b

现在你可以合并

merged_df = pandas.merge(df_a,df_b,on=['merge_addr','merge_comp'],how='inner')