背景
我有 2 个数据框,没有可以将它们合并的通用键。两个 df 都有一个包含“实体名称”的列。一个 df 包含 8000 多个实体,另一个接近 2000 个实体。
样本数据 :
vendor_df=
Name of Vendor City State ZIP
FREDDIE LEES AMERICAN GOURMET SAUCE St. Louis MO 63101
CITYARCHRIVER 2015 FOUNDATION St. Louis MO 63102
GLAXOSMITHKLINE CONSUMER HEALTHCARE St. Louis MO 63102
LACKEY SHEET METAL St. Louis MO 63102
regulator_df =
Name of Entity Committies
LACKEY SHEET METAL Private
PRIMUS STERILIZER COMPANY LLC Private
HELGET GAS PRODUCTS INC Autonomous
ORTHOQUEST LLC Governmant
问题代码:
我必须模糊匹配这两个(
Name of vendor
和 Name of Entity
)列的实体并获得分数。因此,需要知道数据帧 1 的第一个值( vendor_df
)是否与数据帧 2( regulator_df )的 2000 个实体中的任何一个匹配。我检查过的 StackOverflow 链接 :
fuzzy match between 2 columns (Python)
create new column in dataframe using fuzzywuzzy
Apply fuzzy matching across a dataframe column and save results in a new column
代码
import pandas as pd
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
vendor_df = pd.read_excel('C:\\Users\\40101584\\Desktop\\AUS CUB AML\\Vendors_Sheet.xlsx', sheet_name=0)
regulator_df = pd.read_excel('C:\\Users\\40101584\\Desktop\\AUS CUB AML\\Regulated_Vendors_Sheet.xlsx', sheet_name=0)
compare = pd.MultiIndex.from_product([vendor_df['Name of vendor'],
regulator_df['Name of Entity']]).to_series()
def metrics(tup):
return pd.Series([fuzz.ratio(*tup),
fuzz.token_sort_ratio(*tup)],
['ratio', 'token'])
#compare.apply(metrics) -- Either this works or the below line
result = compare.apply(metrics).unstack().idxmax().unstack(0)
以上代码问题 :
如果两个数据框很小,代码就可以工作,但是当我提供完整的数据集时,它会花费很长时间。以上代码取自第三个链接。
如果同样的事情可以快速工作或可以使用大型数据集,任何解决方案?
更新 1
如果我们通过或硬编码一个分数,比如 80 ,这将仅过滤系列/数据帧,那么上面的代码是否可以做得更快? 80 ?
最佳答案
下面的解决方案比我发布的要快,但如果有人有更快的方法,请告诉:
matched_vendors = []
for row in vendor_df.index:
vendor_name = vendor_df.get_value(row,"Name of vendor")
for columns in regulator_df.index:
regulated_vendor_name=regulator_df.get_value(columns,"Name of Entity")
matched_token=fuzz.partial_ratio(vendor_name,regulated_vendor_name)
if matched_token> 80:
matched_vendors.append([vendor_name,regulated_vendor_name,matched_token])
关于python - 不同数据框的模糊匹配列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52256560/