![](/img/trans.png)
[英]How to compare and correct each value in dataframe_1's column with all values in each other dataframe_2's columns?
[英]What's the best way to use fuzzywuzzy to compare each value of a column with all the values of a separate dataframe's column?
在这方面度过了一段非常艰难的时光。 假设我有两个数据框,一个有水果,另一个有水果糖的类型。 每个数据框中还有很多其他数据。 所以它看起来像这样:
fruit:
fruitId fruitName
0 1 banana
1 2 orange
2 3 apple
3 4 pear
4 5 lemon
candy:
candyId candyName fruitId
0 1 Orange Julius null
1 2 Bananarama null
2 3 Sour Lemon Drops null
3 4 Chocolate Bar null
4 5 Applicious null
我需要将candyName
与正确的水果匹配,然后将相应的fruitId
放入candy
dataframe 中的fruitId
列中。为了我的目的,假设.contains
根本不起作用; candyName
列中有太多创造性的拼写和完全错误的拼写。
我试图定义一个使用 fuzzywuzzy 的 function,然后在.map
中使用它,但我无法让 function 工作。 它需要检查第一个 df 的每个值以查看它是否在第二个中,然后移动到下一个值,等等。我最终构建的函数一直想在它们 (a) 相同的地方进行比较dataframe,或 (b) 在同一行。
我确实找到了解决这个问题的方法,但它很难看,因为它使用了你不应该使用的 iterrows() 。 这里是:
import pandas as pd
from fuzzywuzzy import fuzz
candy_file = 'candy.csv'
fruit_file = 'fruits.csv'
candy = pd.read_csv(candy_file)
fruit = pd.read_csv(fruit_file)
dict = {}
for i, row1 in candy.iterrows():
for j, row2 in fruit.iterrows():
if fuzz.partial_ratio(row1['candyName'], row2['fruitName']) >= 80:
dict[row1['candyName']] = row2['fruitId']
candy['fruitId'] = candy['candyName'].map(dict)
这需要永远。 比如,10 分钟完成 500 行。 有一个更好的方法吗? 我已经为更快的函数编写了大约一百个不同的代码片段,但没有取得任何进展。
谢谢!
它很慢,因为你目前在 O(N^2) 中工作。
与其使用 iterrows,不如使用字典来迭代。 这可以通过以下方式完成:
candydict = candy.to_dict{}
fruitdict = fruit.to_dict{}
for k,v in candydict.items():
for k2,v2 in fruitdict.items():
#do the rest of your comparisons here
这应该会大大加快速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.