将每一行与数据框中的所有行进行比较,并将结果保存在每一行的列表中 [英] Compare each row with all rows in data frame and save results in list for each row
问题描述
我尝试用fuzzywuzzy.fuzzy.partial_ratio() >= 85
将每一行与pandas数据框中的所有行进行比较,并将结果写在每一行的列表中.
I try to compare each row with all rows in a pandas dataframe with fuzzywuzzy.fuzzy.partial_ratio() >= 85
and write the results in a list for each row.
示例:
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6], 'name': ['dog', 'cat', 'mad cat', 'good dog', 'bad dog', 'chicken']})
我想在fuzzywuzzy
库中使用pandas函数来获取结果:
I want to use a pandas function with the fuzzywuzzy
library to get the result:
id name match_id_list
1 dog [4, 5]
2 cat [3, ]
3 mad cat [2, ]
4 good dog [1, 5]
5 bad dog [1, 4]
6 chicken []
但是我不知道如何得到这个.
But I don't understand how to get this.
推荐答案
第一步是找到与给定name
条件匹配的索引.由于partial_ratio
仅接受字符串,因此我们将apply
放入数据帧:
The first step would be to find the indices that match the condition for a given name
. Since partial_ratio
only takes strings, we apply
it to the dataframe:
name = 'dog'
df.apply(lambda row: (partial_ratio(row['name'], name) >= 85), axis=1)
然后我们可以使用enumerate
和列表理解来生成布尔数组中的true
索引列表:
We can then use enumerate
and list comprehension to generate the list of true
indices in the boolean array:
matches = df.apply(lambda row: (partial_ratio(row['name'], name) >= 85), axis=1)
[i for i, x in enumerate(matches) if x]
让我们将所有这些放到一个函数中:
Let's put all this inside a function:
def func(name):
matches = df.apply(lambda row: (partial_ratio(row['name'], name) >= 85), axis=1)
return [i for i, x in enumerate(matches) if x]
我们现在可以将函数应用于整个数据框:
We can now apply the function to the entire dataframe:
df.apply(lambda row: func(row['name']), axis=1)
这篇关于将每一行与数据框中的所有行进行比较,并将结果保存在每一行的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!