Search code examples
pythonpandasjupyter-notebookserieskeyerror

KeyError in Pandas for a correct key


Code run in 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']

code image


I am getting a key error (with the following error message) here even when I have put in a correct index

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'

Solution

  • Try running the code you have mentioned as 'Code in Jupyter' it will run. In your image you have not assigned the pd.series to a variable. That is the issue.

    I have tried the following and it works:

    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']