[英]How would I join two dataframe based on a partial string match?
I have two dataframes and want to join them based on three fields, A
, B
, and C
. 我有两个数据框,希望基于三个字段
A
, B
和C
来加入它们。 However, A
and B
are numeric values and I want to them match exactly in my join/merge but C
is a string value and I want at least 80% match (similarity), ie if A
and B
have the same values in both dataframes and the value of C
in the first dataframe is abcde
and in the second one is abcdf
I still want to consider this record in my result. 但是,
A
和B
是数值,我希望它们在联接/合并中完全匹配,但是C
是字符串值,并且我希望至少80%匹配(相似性),即,如果A
和B
在两个数据帧中都具有相同的值而第一个数据帧中C
的值是abcde
,第二个数据帧中的C
的值是abcdf
我仍然想在结果中考虑该记录。 How can I implement this in python? 如何在python中实现呢?
You can using fuzzywuzzy
您可以使用
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
I would probably merge first on only A and B, then filter out any rows that have low similarity on the C column, so something like: 我可能首先只在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]
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.