基于另一DataFrame修正客户DataFrame中地点列的拼写错误
问题描述
我有两个Pandas DataFrame:location和customer,具体定义如下:
import pandas as pd location = pd.DataFrame({'city': ['RIYADH','SEOUL','BUSAN','TOKYO','OSAKA'], 'country': ['Saudi Arabia','South Korea','South Korea','Japan','Japan']})
customer = pd.DataFrame({'id': [1001,2002,3003,4004,5005,6006,7007,8008,9009], 'city': ['tokio','Sorth KOREA','riadh','JAPANN','tokyo','osako','Arab Saudi','SEOUL','buSN']})
需要根据location里的city和country列,修正customer中地点列的拼写错误,最终得到如下结果:
id location 1001 TOKYO 2002 South Korea 3003 RIYADH 4004 Japan 5005 TOKYO 6006 OSAKA 7007 Saudi Arabia 8008 SEOUL 9009 BUSAN
解决方案
用fuzzywuzzy库做模糊匹配就能解决这个问题——它能识别拼写错误、大小写混乱的字符串,匹配到location里的正确值。
1. 先安装依赖
如果没装过fuzzywuzzy,先执行:
pip install fuzzywuzzy python-Levenshtein
python-Levenshtein是可选依赖,安装后能提升匹配速度。
2. 编写代码实现
import pandas as pd from fuzzywuzzy import process # 定义两个原始DataFrame location = pd.DataFrame({'city': ['RIYADH','SEOUL','BUSAN','TOKYO','OSAKA'], 'country': ['Saudi Arabia','South Korea','South Korea','Japan','Japan']}) customer = pd.DataFrame({'id': [1001,2002,3003,4004,5005,6006,7007,8008,9009], 'city': ['tokio','Sorth KOREA','riadh','JAPANN','tokyo','osako','Arab Saudi','SEOUL','buSN']}) # 构建匹配候选:把所有正确的城市、国家转成小写当key,对应正确格式的value candidates = {} for city in location['city']: candidates[city.lower()] = city for country in location['country'].unique(): candidates[country.lower()] = country # 定义修正函数:给一个输入字符串,返回匹配到的正确地点 def fix_location(input_str): input_lower = input_str.lower() # 找最相似的候选,设置匹配阈值80(分数越高匹配越严格) best_match, score = process.extractOne(input_lower, candidates.keys()) if score >= 80: return candidates[best_match] return None # 低匹配度的情况可根据需求调整,示例里所有输入都能匹配到 # 应用函数生成结果列 customer['location'] = customer['city'].apply(fix_location) # 提取需要的列 final_result = customer[['id', 'location']] print(final_result)
运行结果
id location 0 1001 TOKYO 1 2002 South Korea 2 3003 RIYADH 3 4004 Japan 4 5005 TOKYO 5 6006 OSAKA 6 7007 Saudi Arabia 7 8008 SEOUL 8 9009 BUSAN
关键点说明
- 统一转小写是为了消除大小写差异对匹配的干扰,比如
riadh能精准匹配到RIYADH; - 匹配阈值设为80是适中值,遇到更离谱的拼写错误可适当调低;
- 候选集包含城市和国家两类数据,所以像
Sorth KOREA能匹配到South Korea,Arab Saudi能匹配到Saudi Arabia。
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

