How to Fix: KeyError in Pandas
Last Updated :
28 Nov, 2021
In this article, we will discuss how to fix the KeyError in pandas. Pandas KeyError occurs when we try to access some column/row label in our DataFrame that doesn’t exist. Usually, this error occurs when you misspell a column/row name or include an unwanted space before or after the column/row name.
The link to dataset used is here
Example
Python3
import pandas as pd
df = pd.read_csv( 'data.csv' )
|
Output:
Reproducing keyError :
output:
KeyError: 'country'
Since there is no column with the name country we get a KeyError.
How to Fix the KeyError?
We can simply fix the error by correcting the spelling of the key. If we are not sure about the spelling we can simply print the list of all column names and crosscheck.
Python3
print (df.columns.tolist())
|
Output:
['Country', 'Age', 'Salary', 'Purchased']
Using the Correct Spelling of the Column
Output:
0 France
1 Spain
2 Germany
3 Spain
4 Germany
5 France
6 Spain
7 France
8 Germany
9 France
Name: Country, dtype: object
If we want to avoid errors raised by the compiler when an invalid key is passed, we can use df.get(‘your column’) to print column value. No error is raised if the key is invalid.
Syntax : DataFrame.get( ‘column_name’ , default = default_value_if_column_is_not_present)
Python3
df.get( 'country' , default = "no_country" )
|
Output:
'no_country'
But when we will use correct spelling we will get the value of the column instead of the default value.
Python3
df.get( 'Country' , default = "no_country" )
|
Output:
0 France
1 Spain
2 Germany
3 Spain
4 Germany
5 France
6 Spain
7 France
8 Germany
9 France
Name: Country, dtype: object
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...