Open In App

How to Fix: KeyError in Pandas

Last Updated : 28 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




# importing pandas as pd
import pandas as pd
  
# using .read_csv method to import dataset
df = pd.read_csv('data.csv')


Output:

Reproducing keyError :

Python3




# intentionally passing wrong spelling of
# the key present in dataset
df['country']


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




# printing all columns of the dataframe
print(df.columns.tolist())


Output:

['Country', 'Age', 'Salary', 'Purchased']

Using the Correct Spelling of the Column

Python3




# printing the column 'Country'
df['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

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




# Again using incorrect spelling of the 
# column name 'Country' but this time
# we will use df.get method with default 
# value "no_country"
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




# printing column 'Country'
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
Previous
Next
Share your thoughts in the comments

Similar Reads