模糊字符串与熊猫匹配和FuzzyWuzzy; KeyError:'name'

时间:2019-09-25 09:31:34

标签: python-3.x pandas fuzzywuzzy

我有一个看起来像这样的数据文件- wrong country names

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

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'

对此将提供任何帮助!非常感谢!

1 个答案:

答案 0 :(得分:0)

您的代码包含例如wrong_names=df['name'].dropna().values(是 在您的“追溯”中被称为“违规”行。

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

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

返回到Traceback:最后有错误消息: KeyError: 'name'

因此,您尝试访问不存在的列。

我还注意到了另一个细节:values属性包含基础 Numpy 数组,而 process.extractOne 需要“普通的” Python 列表(使用字符串,以执行匹配)

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

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

与其他指令相同。

相关问题