How to fix KeyError(key) from err

You came here because you encountered a KeyError (key) from err error in Pandas.

KeyError Pandas issue

In my case, the full text of the exception is:

C:\Users\panda\PandasHowTo\venv\Scripts\python.exe C:/Users/panda/PandasHowTo/new.py
Traceback (most recent call last):
  File "C:\Users\panda\PandasHowTo\venv\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_loc
    return self._engine.get_loc(casted_key)
  File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'C'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\panda\PandasHowTo\new.py", line 4, in 
    print(df['C'])
  File "C:\Users\panda\PandasHowTo\venv\lib\site-packages\pandas\core\frame.py", line 3455, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\panda\PandasHowTo\venv\lib\site-packages\pandas\core\indexes\base.py", line 3363, in get_loc
    raise KeyError(key) from err
KeyError: 'C'

Process finished with exit code 1

If your KeyError looks similar then the article below will solve the problem you have encountered.

Why do i see KeyError

The KeyError appeared because you are referring to a key that does not exist.

In most cases, the KeyError in Pandas occurs in two different cases:
1. you made a typo
2. the dataset has been modified and the row or column is no longer available or has been renamed

How to fix KeyError

There are several ways to fix KeyError in Pandas.

  • Check the spelling and correct any typos.
  • Add an exception handler to prevent reference to a key that does not exist.
  • Instead of referring to a column / row by name, use an index reference.

To fix the KeyError, you need to ensure that the column or index label you are trying to access exists in the dataframe. You can check the available columns and index labels using the df.columns and df.index properties, respectively.

If you want to access a column by name but don’t mind if it doesn’t exist, you can use the get method:

column = df.get("non_existent_column")
if column is not None:
    print(column)
else:
    print("Column does not exist")
</pre

This Post Has 3 Comments

Leave a Reply