清单效果中的Python模糊匹配字符串

时间:2019-05-08 12:29:03

标签: python duplicates string-matching fuzzy-search

我正在检查在4个相同的数据框列中是否有相似的结果(模糊匹配),我以下面的代码为例。当我将其应用于实际的40.000行x 4列数据集时,将始终以整数运行。问题是代码太慢。例如,如果我将数据集限制为10个用户,则需要8分钟来计算,而要花20到19分钟。我有什么想念的吗?我不知道为什么要花这么长时间。我希望能在2小时或更短的时间内得到所有结果。任何提示或帮助将不胜感激。

from fuzzywuzzy import process
dataframecolumn = ["apple","tb"]
compare = ["adfad","apple","asple","tab"]
Ratios = [process.extract(x,compare) for x in dataframecolumn]
result = list()
for ratio in Ratios:
    for match in ratio:
        if match[1] != 100:
            result.append(match)
            break
print (result) 

输出: [('asple',80),('tab',80)]

1 个答案:

答案 0 :(得分:1)

  

通过编写矢量化操作并避免循环来显着提高速度

导入必要的程序包

from fuzzywuzzy import fuzz
import pandas as pd
import numpy as np

从第一个列表创建数据框

dataframecolumn = pd.DataFrame(["apple","tb"])
dataframecolumn.columns = ['Match']

从第二个列表创建数据框

compare = pd.DataFrame(["adfad","apple","asple","tab"])
compare.columns = ['compare']

通过引入键合并-笛卡尔积

dataframecolumn['Key'] = 1
compare['Key'] = 1
combined_dataframe = dataframecolumn.merge(compare,on="Key",how="left")
combined_dataframe = combined_dataframe[~(combined_dataframe.Match==combined_dataframe.compare)]

向量化

def partial_match(x,y):
    return(fuzz.ratio(x,y))
partial_match_vector = np.vectorize(partial_match)

使用矢量化并通过将阈值置于得分上来获得理想的结果

combined_dataframe['score']=partial_match_vector(combined_dataframe['Match'],combined_dataframe['compare'])
combined_dataframe = combined_dataframe[combined_dataframe.score>=80]

结果

+--------+-----+--------+------+
| Match  | Key | compare | score
+--------+-----+--------+------+
| apple  | 1   |   asple |    80
|  tb    | 1   |   tab   |    80
+--------+-----+--------+------+