如何解决数据框中每行两列的字符串匹配
ID String1 String2
1 The big black wolf The small wolf
2 Close the door on way out door the Close
3 where's the money where is the money
4 123 further out out further
在做模糊字符串匹配之前,我想交叉表 String1 和 String2 列中的每一行,类似于 Python fuzzy string matching as correlation style table/matrix。
我的挑战是,我发布的链接中的解决方案仅在 String1 和 String2 中的字数相同时才有效。其次,该解决方案查看列中的所有行,而我希望我的只进行逐行比较。
建议的解决方案应该对第 1 行进行类似比较的矩阵,例如:
string1 The big black wolf Maximum
string2
The 100 0 0 0 100
small 0 0 0 0 0
wolf 0 0 0 100 100
ID String1 String2 Matching_Average
1 The big black wolf The small wolf 66.67
2 Close the door on way out door the Close
3 where's the money where is the money
4 123 further out out further
其中匹配平均值是 'maximum' 列的总和除以 String2 中的单词数
解决方法
您可以先从 2 系列中得到哑元,然后得到列的交集,将它们相加并除以第二列的哑元:
a = df['String1'].str.get_dummies(' ')
b = df['String2'].str.get_dummies(' ')
u = b[b.columns.intersection(a.columns)]
df['Matching_Average'] = u.sum(1).div(b.sum(1)).mul(100).round(2)
print(df)
ID String1 String2 Matching_Average
0 1 The big black wolf The small wolf 66.67
1 2 Close the door on way out door the Close 100.00
2 3 where's the money where is the money 50.00
3 4 123 further out out further 100.00
否则,如果您可以使用字符串匹配算法,则可以使用 difflib
:
from difflib import SequenceMatcher
[SequenceMatcher(None,x,y).ratio() for x,y in zip(df['String1'],df['String2'])]
#[0.625,0.2564102564102564,0.9142857142857143,0.6153846153846154]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。