Python pandas,用已知列表中最接近的字符串匹配替换数据框列中的所有元素

Python pandas, substitute all elements in a dataframe column with closest string match from known list

我有一个数据框,其中列中的值是经常拼写错误的字符串,例如:

col01 | col02 | name
-----------------------
 ---  |  ---  |  mrk 
 ---  |  ---  |  anth3n7 
 ---  |  ---  |  j4ck 

以及该列可能的正确值列表

possible_names = ['mark', 'anthony', 'jack']

我想遍历 'name' 列的元素,并从正确名称列表中获得最接近的匹配项,这样我最终会得到:

col01 | col02 | name      |   correct_name
-----------------------------------------
 ---  |  ---  |  mrk      |       mark
 ---  |  ---  |  anth3n7  |      anthony
 ---  |  ---  |  j4ck     |       jack

我尝试使用此代码:

df_names = pd.read_csv('names/wrong.csv')
possible_names = ['mark', 'anthony', 'jack']
df_names['correct_name'] = difflib.get_close_matches(df_names['name'], possible_names)

但我收到错误消息:

ValueError: Length of values (0) does not match length of index (3)

使用:

import difflib

import pandas as pd

df = pd.DataFrame(data=["mrk", "anth3n7", "j4ck"], columns=["name"])
possible_names = ['mark', 'anthony', 'jack']

df["correct_name"] = df["name"].apply(lambda x: difflib.get_close_matches(x, possible_names)[0])
print(df)

输出

      name correct_name
0      mrk         mark
1  anth3n7      anthony
2     j4ck         jack

作为 .apply 的替代方法,您可以使用列表理解:

df["correct_name"] = [difflib.get_close_matches(name, possible_names)[0] for name in df["name"]]

更新

对于不匹配的情况,一种方法是使用:

possible_names = ['anthony', 'jack']
df["correct_name"] = [next(iter(difflib.get_close_matches(name, possible_names)), name) for name in df["name"]]
print(df)

输出

      name correct_name
0      mrk          mrk
1  anth3n7      anthony
2     j4ck         jack

让我们试试

from fuzzywuzzy import process

df['new']=df.Name.apply(lambda x : [process.extract(x, possible_names, limit=1)][0][0][0])