pandas 将每一行与数据框中的所有行进行比较,并将结果保存在每行的列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35459316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compare each row with all rows in data frame and save results in list for each row
提问by pirr
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.
我尝试将每行与Pandas数据fuzzywuzzy.fuzzy.partial_ratio() >= 85
框中的所有行进行比较,并将结果写入每行的列表中。
Example:
例子:
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6], 'name': ['dog', 'cat', 'mad cat', 'good dog', 'bad dog', 'chicken']})
I want to use a pandas function with the fuzzywuzzy
library to get the result:
我想在fuzzywuzzy
库中使用 pandas 函数来获得结果:
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.
但我不明白如何得到这个。
回答by IanS
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
。由于partial_ratio
只需要字符串,我们apply
把它放到数据帧中:
name = 'dog'
df.apply(lambda row: (partial_ratio(row['name'], name) >= 85), axis=1)
We can then use enumerate
and list comprehension to generate the list of true
indices in the boolean array:
然后我们可以使用enumerate
和列表理解来生成true
布尔数组中的索引列表:
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)