【发布时间】:2021-07-22 10:56:35
【问题描述】:
所以我希望修改此代码以减少fuzzywuzzy 库的运行时间。目前,一个800行的数据集大约需要一个小时,当我在一个4.5K行的数据集上使用它时,它运行了将近6个小时,仍然没有结果。我不得不停止内核。
我需要在至少 20K 的数据上使用此代码。任何人都可以建议对此代码进行任何编辑以更快地获得结果吗?这是代码 -
import pandas as pd
import numpy as np
from fuzzywuzzy import fuzz,process
df = pd.read_csv(r'path')
df.head()
data = df['Body']
print(data)
clean = []
threshold = 80
for row in data:
# score each sentence against each other
# [('string', score),..]
scores = process.extract(row, data, scorer=fuzz.token_set_ratio)
# basic idea is if there is a close second match we want to evaluate
# and keep the longer of the two
if scores[1][1] > threshold:
clean.append(max([x[0] for x in scores[:2]],key=len))
else:
clean.append(scores[0][0])
# remove dupes
clean = set(clean)
#converting 'clean' list to dataframe and giving the column name for the cleaned column
clean_data = pd.DataFrame(clean, columns=['Body'])
clean_data.to_csv(r'path')
这就是我的数据的样子 -
https://docs.google.com/spreadsheets/d/1p9RC9HznhdJFH4kFYdE_TgnHdoRf8P6gTEAkB3lQWEE/edit?usp=sharing
因此,如果您注意到第 14 和 15 行,并且第 19 和 20 行是部分重复的,我希望代码能够识别这些句子,并删除较短的句子。
更新-
我对@Darryl G给出的rapidfuzz解决方案做了一个小改动,现在代码看起来像这样-
`import pandas as pd
import numpy as np
import openpyxl
from rapidfuzz.fuzz import token_set_ratio as rapid_token_set_ratio
from rapidfuzz import process as process_rapid
from rapidfuzz import utils as rapid_utils
import time
df = pd.read_excel(r'path')
data = df['Body']
print(data)
def excel_sheet_to_dataframe(path):
'''
Loads sheet from Excel workbook using openpyxl
'''
wb = openpyxl.load_workbook(path)
ws = wb.active
data = ws.values
# Get the first line in file as a header line
columns = next(data)[0:]
return pd.DataFrame(data, columns=columns)
clean_rapid = []
threshold = 80
def process_rapid_fuzz(data):
'''
Process using rapid fuzz rather than fuzz_wuzzy
'''
series = (rapid_utils.default_process(d) for d in data) # Pre-process to make lower-case and remove non-alphanumeric
# characters (generator)
processed_data = pd.Series(series)
for query in processed_data:
scores = process_rapid.extract(query, processed_data, scorer=rapid_token_set_ratio, score_cutoff=threshold)
if len(scores) > 1 and scores[1][1] > threshold:
m = max(scores[:2], key = lambda k:len(k[0])) # Of up to two matches above threshold, takes longest
clean_rapid.append(m[0]) # Saving the match index
else:
clean_rapid.append(query)
################ Testing
t0 = time.time()
df = excel_sheet_to_dataframe(r'path') # Using Excel file in working folder
# Desired data in body column
data = df['Body'].dropna() # Dropping None rows (few None rows at end after Excel import)
result_fuzzy_rapid = process_rapid_fuzz(data)
print(f'Elapsed time {time.time() - t0}')
# remove dupes
clean_rapid = set(clean_rapid)
#converting 'clean' list to dataframe and giving the column name for the cleaned column
clean_data = pd.DataFrame(clean_rapid, columns=['Body'])
#exporting the cleaned data
clean_data.to_excel(r'path')`
现在的问题是,在输出文件中,所有的句号等都被删除了。我怎样才能保留它们?
【问题讨论】:
-
您能否提供您 CSV 文件中的一小段摘录?
-
查看 maxbachmann 在Vectorizing or Speeding up Fuzzywuzzy String Matching on PANDAS Column 中的答案,该答案对类似问题产生了 10 倍的改进。
-
@AndyKnight 嗨,我添加了我的数据外观的 sn-p。希望对你有帮助
-
@Shrumo——不仅仅是使用一个数据框的单列(即列“org_name”)的引用。它不是使用fuzzy_wuzzy 来查找整列中每一行的最接近的匹配项吗?这似乎与您正在做的事情相似。
-
@DarrylG 嗨,我确实看到了该解决方案,但是,我的目标是识别此类重复项并将其删除。我分享的代码可以完成这项工作,只是它对于投标数据集非常耗时且不切实际。希望有一些意见。
标签: python data-cleaning fuzzywuzzy drop-duplicates rapidfuzz