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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:42:50  来源:igfitidea点击:

Compare each row with all rows in data frame and save results in list for each row

pythonpandasdata-analysisfuzzywuzzy

提问by pirr

I try to compare each row with all rows in a pandas dataframe with fuzzywuzzy.fuzzy.partial_ratio() >= 85and 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 fuzzywuzzylibrary 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_ratioonly takes strings, we applyit 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 enumerateand list comprehension to generate the list of trueindices 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)