【问题标题】:String matching per row of two columns in a dataframe数据框中每行两列的字符串匹配
【发布时间】:2021-04-28 14:45:00
【问题描述】:

假设我有一个如下所示的 pandas 数据框:

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

其中匹配平均值是“最大”列的总和除以 String2 中的单词数

【问题讨论】:

  • 其中匹配平均值是“最大”列的总和除以 String1 中的单词数 - 你的意思是 String2 而不是 String1?
  • 这是正确的@anky,现在将编辑。

标签: python-3.x pandas matrix fuzzy


【解决方案1】:

你可以先得到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]

【讨论】:

  • 谢谢@anky,如果我想使用from fuzzywuzzy import fuzz 模糊匹配字符串怎么办?
  • 既然你只是想在导入后比较你想要的[fuzz.ratio(x,y) for x,y in zip(df['String1'],df['String2'])],你也可以试试fuzz.partial_ratio,这取决于你的requirement(check this)
  • 花了我一段时间才弄明白,但我认为您的算法是在比较之前对 a 和 b 中的所有行进行虚拟编码。 ID = 2 的结果很明显,我希望结果为 100,而不是 133,但由于 ID = 3 的 the,它给出了更高的分数。我只想在比较之前逐行模拟代码。有意义吗?
  • @user1783739 编辑了我的答案(我在定义 u 时弄乱了部分代码),现在请检查?
猜你喜欢
  • 1970-01-01
  • 2020-10-23
  • 2017-01-21
  • 2017-10-01
  • 1970-01-01
  • 2021-09-08
相关资源
最近更新 更多