【问题标题】:How would I join two dataframe based on a partial string match?如何根据部分字符串匹配加入两个数据框?
【发布时间】:2018-07-27 19:35:09
【问题描述】:

我有两个数据框,想根据三个字段加入它们,ABC。但是,AB 是数值,我希望它们在我的加入/合并中完全匹配,但 C 是一个字符串值,我希望至少 80% 匹配(相似性),即如果 AB 在两个数据帧中具有相同的值,第一个数据帧中C 的值是abcde,第二个是abcdf 我仍然想在我的结果中考虑这条记录。我如何在 python 中实现这个?

【问题讨论】:

    标签: python pandas string-matching


    【解决方案1】:

    您可以使用fuzzywuzzy

    from fuzzywuzzy import fuzz
    
    df1=pd.DataFrame({'A':[1,3,2],'B':[2,2,3],'C':['aad','aac','aad']})
    
    df2=pd.DataFrame({'A':[1,2,2],'B':[2,2,3],'C':['aad','aab','acd']})
    
    mergedf1=df1.merge(df2,on=['A','B'])
    
    mergedf1['ratio']=[fuzz.ratio(x,y) for x, y in zip(mergedf1['C_x'],mergedf1['C_y'])]
    mergedf1#score list here , you can cut the data frame by your own limit 
    Out[265]: 
       A  B  C_x  C_y  ratio
    0  1  2  aad  aad    100
    1  2  3  aad  acd     67
    

    【讨论】:

      【解决方案2】:

      我可能会先合并 A 和 B,然后过滤掉 C 列上相似度低的任何行,例如:

      result = df1.merge(df2, on=['A', 'B'])
      
      # assuming sim is the similarity function that you created to calculate the similarity
      idx = result.apply(lambda x: sim(c['C_x', 'C_y']) >= 0.8, axis=1)
      result = result[idx]
      

      希望对你有帮助!

      【讨论】:

      • sim是他需要做的新功能?
      • @RafaelC 我花了一些时间找到函数sim ...LOL
      • @Wen 哦,这就是OP想要计算相似度的方式,已编辑,谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      相关资源
      最近更新 更多