簡體   English   中英

Pandas 中的 KeyError 以獲得正確的密鑰

[英]KeyError in Pandas for a correct key

在 jupyter notebook 中運行的代碼

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'

嘗試運行您提到的“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']

在筆記本中的評估 [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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM