Pandas 中出现正确密钥的 KeyError

KeyError in Pandas for a correct key

jupyter 笔记本中的代码 运行

import pandas as pd
import numpy as np
myindex = ['USA','Canada','Mexico']
mydata = [1776,1867,1821]
myser = pd.Series(data=mydata,index=myindex)
myser['USA']

代码图片


即使我输入了正确的索引,我仍然在这里遇到一个关键错误(带有以下错误消息)

KeyError                                  Traceback (most recent call last)
<ipython-input-41-422adf17bf03> in <module>
----> 1 myser['USA']

D:\Anaconda\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    851 
    852         elif key_is_scalar:
--> 853             return self._get_value(key)
    854 
    855         if is_hashable(key):

D:\Anaconda\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
    959 
    960         # Similar to Index.get_value, but we do not fall back to positional
--> 961         loc = self.index.get_loc(label)
    962         return self.index._get_values_for_loc(self, loc, label)
    963 

D:\Anaconda\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
    352                 except ValueError as err:
    353                     raise KeyError(key) from err
--> 354             raise KeyError(key)
    355         return super().get_loc(key, method=method, tolerance=tolerance)
    356 

KeyError: 'USA'

您的笔记本中的评估 [34] 和评估 [43] 之间的系列可能有问题。这按预期工作:

myindex=['USA', 'Canada', 'Mexico']
mydata=[1776,1867,1821]
myser=pd.Series(data=mydata, index=myindex)
myser

输出:

USA       1776
Canada    1867
Mexico    1821
dtype: int64
>>> myser[0]
1776

>>> myser['USA']
1776

尝试 运行 将您提到的代码 'Code in Jupyter' 设置为 运行。在您的图像中,您没有将 pd.series 分配给变量。就是这个问题。

我已经尝试了以下并且有效:

import pandas as pd
my_index = ['Usa', 'Canada', 'Mexico']
my_data = [10, 20, 30]
my_ser_1 = pd.Series(data = my_data, index = my_index)
my_ser_1['Usa']