1

客观的

  • 给定一个 excel 文件(充满拼写错误),使用 FuzzyWuzzy 将拼写错误与accepted列表进行比较和匹配。
  • accepted用最接近的匹配更正错字填充的 excel 文件。

方法

  1. 使用熊猫导入 Excel 文件
  2. 将原始的、错字填充的 excel 文件推送到数据框中
  3. 创建accepted数据框
  4. accepted使用FuzzyWuzzy比较错字数据框和数据框
  5. 返回原始拼写、接受的拼写和匹配分数
  6. 将关联的、可接受的拼写附加到所有拼写的原始 excel 文件/行

代码

#Load Excel File into dataframe
xl = pd.read_excel(open("/../data/expenses.xlsx",'rb'))

excel数据框

#Let's clarify how many similar categories exist... 
q = """
    SELECT DISTINCT Expense 
    FROM xl
    ORDER BY Expense ASC

"""

expenses = sqldf(q)
print(expenses)

相似类别

#Let's add some acceptable categories and use fuzzywuzzy to match
accepted = ['Severance', 'Legal Fees', 'Import & Export Fees', 'I.T. Fees', 'Board Fees', 'Acquisition Fees']

#select from the list of accepted values and return the closest match
process.extractOne("Company Acquired",accepted,scorer=fuzz.token_set_ratio)

('Acquisition Fees', 38) 分数不高,但足够高,可以返回预期的输出

!!!!!问题!!!!!

#Time to loop through all the expenses and use FuzzyWuzzy to generate and return the closest matches.
def correct_expense(expense):
    for expense in expenses:
        return expense, process.extractOne(expense,accepted,scorer = fuzz.token_set_ratio)

correct_expense(expenses)

('费用', ('法律费用', 47))

问题

  1. 如您所见,process.extractOne 在逐个测试时运行正确。但是,在循环中运行时,返回值是意外的。我相信我可能会抓住第一列或最后一列,但即使是这样,我也希望“董事费”或“收购”会弹出(参见原始 excel 文件)。
4

2 回答 2

3

我过去这样做的方法是只使用Python 模块中的get_closest_matches函数。difflib然后,您可以创建一个函数来获取最接近的匹配并将其应用于Expense列。

def correct_expense(row):
    accepted = ['Severance', 'Legal Fees', 'Import & Export Fees', 'I.T. Fees', 'Board Fees', 'Acquisition Fees']
    match = get_close_matches(row, accepted, n=1, cutoff=0.3)
    return match[0] if match else ''

df['Expense_match'] = df['Expense'].apply(correct_expense)

Expense这是与列表匹配的值的原始列accepted

在此处输入图像描述

您可能需要微调accepted列表和cutoffget_closest_matches(我发现 0.3 对您的示例数据非常有效)。

对结果满意后,您可以更改函数以覆盖Expense列并使用 pandas DataFrame 方法保存到 Excel to_excel

于 2017-01-02T20:58:37.343 回答
1

这称为地名词典重复数据删除。
您可以通过将杂乱的数据与规范数据(即公报)进行匹配来执行重复数据删除。

pandas-dedupe可以做到这一点。
例子:

import pandas as pd
import pandas_dedupe

clean_data = pd.DataFrame({'street': ['Onslow square', 'Sydney Mews', 'Summer Place', 'Bury Walk', 'sydney mews']})
messy_data = pd.DataFrame({'street_name':['Onslow sq', 'Sidney Mews', 'Summer pl', 'Onslow square', 'Bury walk', 'onslow sq', 'Bury Wall'],
                           'city' : ['London', 'London', 'London', 'London', 'London', 'London', 'London']})

dd = pandas_dedupe.gazetteer_dataframe(
    clean_data, 
    messy_data, 
    field_properties = 'street_name', 
    canonicalize=True,
    )

在此过程中,pandas-dedupe 会要求您将几个示例标记为重复或不同的记录。然后,图书馆将使用这些知识来查找潜在的重复条目,将它们与干净的数据进行匹配,并返回所有相关信息,包括对结果的置信度。

于 2020-12-19T12:11:57.287 回答