Fuzzy String Matching With Pandas and FuzzyWuzzy ;KeyError: 'name'

Fuzzy String Matching With Pandas and FuzzyWuzzy ;KeyError: 'name'

我有这样的数据文件 -

我还有另一个数据文件,其中包含所有正确的国家/地区名称。 为了匹配我在下面使用的两个文件:

from fuzzywuzzy import process
import pandas as pd




names_array=[]
ratio_array=[]
def match_names(wrong_names,correct_names):
    for row in wrong_names:
         x=process.extractOne(row, correct_names)
         names_array.append(x[0])
         ratio_array.append(x[1])
    return names_array,ratio_array



#Wrong country names dataset
df=pd.read_csv("wrong-country-names.csv",encoding="ISO-8859-1")
wrong_names=df['name'].dropna().values

#Correct country names dataset
choices_df=pd.read_csv("country-names.csv",encoding="ISO-8859-1")
correct_names=choices_df['name'].values

name_match,ratio_match=match_names(wrong_names,correct_names)



df['correct_country_name']=pd.Series(name_match)
df['country_names_ratio']=pd.Series(ratio_match)

df.to_csv("string_matched_country_names.csv")

print(df[['name','correct_country_name','country_names_ratio']].head(10))

我收到以下错误:

runfile('C:/Users/Drashti Bhatt/Desktop/untitled0.py', wdir='C:/Users/Drashti Bhatt/Desktop')
Traceback (most recent call last):

  File "<ipython-input-155-a1fd87d9f661>", line 1, in <module>
    runfile('C:/Users/Drashti Bhatt/Desktop/untitled0.py', wdir='C:/Users/Drashti Bhatt/Desktop')

  File "C:\Users\Drashti Bhatt\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Drashti Bhatt\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/Drashti Bhatt/Desktop/untitled0.py", line 17, in <module>
    wrong_names=df['name'].dropna().values

  File "C:\Users\Drashti Bhatt\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Users\Drashti Bhatt\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2659, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc

  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item

      File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item

    KeyError: 'name'

如有任何帮助,我们将不胜感激!非常感谢!

您的代码包含例如wrong_names=df['name'].dropna().values(这是 在您的回溯中提到的 "offending" 行)。

现在看看展示您的 DataFrame 的图片:

  • 它不包含 name 列,
  • 它包含 Country 列。

回到回溯:最后有错误信息: KeyError: 'name'.

所以您试图访问一个不存在的列。

我还注意到另一个细节:values 属性包含底层 Numpy 数组,而 process.extractOne 需要 "ordinary" Python 列表(字符串,执行匹配)。

所以您可能应该将上面的说明更改为:

wrong_names=df['Country'].dropna().values.tolist()

其他指令也一样。