【问题标题】:Find the similarity between a string input and a string column of a Data Frame查找字符串输入与数据框的字符串列之间的相似性
【发布时间】:2019-01-29 18:20:51
【问题描述】:

我有一个 pandas 数据框,其中有两列包含字符串,如下所示:

Col-1                 Col-2
Animal                have an apple
Fruit                 tiger safari
Veg                   Vegetable Market
Flower                Garden

由此我必须创建一个以字符串为参数的函数。

此函数然后检查输入字符串与Col-2 的元素之间的fuzziwuzzy 相似度,并输出计算出的最高相似度对应的Col-1Col-2 的元素。

例如假设输入字符串是Gardening Hobby,这里它将检查与df['Col-2']的所有元素的相似度。该函数发现 GardenGardening Hobby 的相似度最高,得分为 90。那么预期输出为:

I/P               O/P
Gardening Hobby   Garden(60),Flower

【问题讨论】:

  • 你的问题不是很清楚。你在说什么count?为什么字符串BOTH 应该抛出Error in Message?你想计算什么样的相似度?您如何处理输入字符串和Col-2 元素之间计算的相似度?在您的示例中,您如何获得 Garden(60),Flower 作为输出?如果您想得到答案,请让您的问题更清楚。
  • @ysearka..我已经编辑了我的问题..希望现在没问题。
  • 不仅如此,在您的示例中,您检查了输入字符串与df['Col-2'] 的元素之间的相似性,但是在上一段中,您说您还需要计算与第一列的相似性?你的输出中的60 是什么?相似度得分?如果是这样,它是如何计算的?
  • @ysearka..60 是相似度得分。我们必须使用fuzzywuzzy逻辑来计算。我没有计算,只是一个例子。我只需要检查输入字符串与 Col-2 值的相似性。
  • gyx-hh 的解决方案似乎有效,如果解决了您的问题,请考虑接受。

标签: python string pandas nlp fuzzywuzzy


【解决方案1】:

使用 fuzzywuzzy 库尝试以下方法 - tutorial

from fuzzywuzzy import process

search_str = 'Gardening Hobby'
# extract the best match of search_str in df['Col-2']
best_match = process.extractOne(search_str, df['Col-2'])
print(best_match)  # output: ('Garden', 90, 3)  (match,score,index)

# get results for 'Col-1' using the index
res = df.iloc[best_match[2]]['Col-1']
print(res)  # output: 'Flower'

# construct the output string as you wish
'%s(%d), %s' % (best_match[0], best_match[1], res)

# output: 'Garden(90), Flower'

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 2021-03-20
    • 2021-02-23
    • 2019-09-25
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多