python 模糊匹配 合并_是否可以与python pandas进行模糊匹配合并?

本文介绍如何使用Python的difflib库解决DataFrame合并问题,通过get_close_matches函数处理因拼写错误、不同格式导致的名称不一致,实现基于类似度的合并操作,适用于df1与df2中列名的灵活匹配。
摘要由CSDN通过智能技术生成

I have two DataFrames which I want to merge based on a column. However, due to alternate spellings, different number of spaces, absence/presence of diacritical marks, I would like to be able to merge as long as they are similar to one another.

Any similarity algorithm will do (soundex, Levenshtein, difflib's).

Say one DataFrame has the following data:

df1 = DataFrame([[1],[2],[3],[4],[5]], index=['one','two','three','four','five'], columns=['number'])

number

one 1

two 2

three 3

four 4

five 5

df2 = DataFrame([['a'],['b'],['c'],['d'],['e']], index=['one','too','three','fours','five'], columns=['letter'])

letter

one a

too b

three c

fours d

five e

Then I want to get the resulting DataFrame

number letter

one 1 a

two 2 b

three 3 c

four 4 d

five 5 e

解决方案

Similar to @locojay suggestion, you can apply difflib's get_close_matches to df2's index and then apply a join:

In [23]: import difflib

In [24]: difflib.get_close_matches

Out[24]:

In [25]: df2.index = df2.index.map(lambda x: difflib.get_close_matches(x, df1.index)[0])

In [26]: df2

Out[26]:

letter

one a

two b

three c

four d

five e

In [31]: df1.join(df2)

Out[31]:

number letter

one 1 a

two 2 b

three 3 c

four 4 d

five 5 e

.

If these were columns, in the same vein you could apply to the column then merge:

df1 = DataFrame([[1,'one'],[2,'two'],[3,'three'],[4,'four'],[5,'five']], columns=['number', 'name'])

df2 = DataFrame([['a','one'],['b','too'],['c','three'],['d','fours'],['e','five']], columns=['letter', 'name'])

df2['name'] = df2['name'].apply(lambda x: difflib.get_close_matches(x, df1['name'])[0])

df1.merge(df2)

对于Excel表格的名字进行模糊匹配合并,可以使用Python的`fuzzywuzzy`库和`pandas`库。 `fuzzywuzzy`库提供了模糊匹配的方法,可以用来比较两个字符串之间的相似度。而`pandas`库则提供了强大的数据处理和合并功能,可以帮助我们对Excel表格进行高效的数据处理。 下面是一个简单的示例代码,展示如何对Excel表格的名字进行模糊匹配合并: ```python from fuzzywuzzy import fuzz import pandas as pd # 读取Excel表格 df = pd.read_excel('example.xlsx') # 将姓名转换为小写,并去除空格 df['姓名'] = df['姓名'].str.lower().str.strip() # 定义匹配函数 def match_names(name, all_names): # 通过计算相似度,找到最接近的名字 best_match = None highest_ratio = 0 for n in all_names: ratio = fuzz.ratio(name, n) if ratio > highest_ratio: best_match = n highest_ratio = ratio if highest_ratio >= 80: return best_match else: return name # 对姓名进行模糊匹配合并 all_names = df['姓名'].unique() df['姓名'] = df['姓名'].apply(match_names, args=(all_names,)) # 将结果保存到新的Excel表格 df.to_excel('merged_names.xlsx', index=False) ``` 在这个示例代码,我们首先使用`pd.read_excel()`方法读取Excel表格,并将姓名列转换为小写,去除空格。然后,定义了一个匹配函数`match_names()`,该函数接受一个名字和所有名字的列表,返回一个最接近的名字。 在`match_names()`函数,我们使用`fuzz.ratio()`方法计算两个字符串之间的相似度,然后选择最相似的名字作为匹配结果。如果相似度高于80%,则认为两个名字是同一个人,返回最相似的名字;否则,返回原始名字。 最后,我们使用`df['姓名'].apply()`方法将匹配函数应用到DataFrame的姓名列,对所有名字进行模糊匹配合并。最终结果存储在一个新的Excel表格`merged_names.xlsx`。 需要注意的是,模糊匹配可能会产生误匹配,因此需要根据实际情况进行调整和验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值