How to Fix: KeyError in Pandas
Last Updated :
28 May, 2025
Pandas KeyError occurs when you try to access a column or row label in a DataFrame that doesn’t exist. This error often results from misspelled labels, unwanted spaces, or case mismatches. This article covers common causes of KeyError in pandas and how to fix them.
1. Column name not found
When working with a pandas DataFrame, you might try to access a column using syntax like df['Gender']. But if that column doesn't actually exist in the DataFrame, pandas will throw a KeyError.
Python
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df['Gender']
Output
KeyError: 'Gender'
Solution: Before trying to access a column, it’s a good practice to check if it exists using the in operator. Here's a safe way to handle it:
Python
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob'], 'Age': [25, 30]})
print(df.columns)
if 'Gender' in df.columns:
print(df['Gender'])
else:
print("Column not exist.")
Output
Index(['Name', 'Age'], dtype='object')
Column not exist.
Explanation: This code safely accesses a column by first printing all column names with df.columns, then checking if 'Gender' exists using the in operator. If it exists, it prints the values otherwise, it shows "Column not exist."
2. Extra spaces in column names
Sometimes a column might seem like it exists, but pandas can't find it because it includes unintended spaces (e.g., ' Name' instead of 'Name'). This usually happens when reading data from CSV or Excel files.
Python
import pandas as pd
df = pd.DataFrame({' Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df['Name']
Output
KeyError: 'Name'
Solution: Use .str.strip() to remove any leading/trailing spaces from column names before accessing them.
Python
import pandas as pd
df = pd.DataFrame({' Name': ['Alice', 'Bob'], 'Age': [25, 30]})
df.columns = df.columns.str.strip()
df['Name']
Output
Using strip()Explanation: It first creates a DataFrame with a column named ' Name' (with a leading space). Then, it removes any spaces from the column names using df.columns.str.strip(). After that, accessing the column 'Name' works correctly without causing a KeyError.
3. Accessing row with invalid label using iloc[]
If you try to access a row label using df.loc['c'], and 'c' does not exist in the index, pandas raises a KeyError.
Python
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob']}, index=['a', 'b'])
df.loc['c']
Output
KeyError: 'c'
Solution: Always check if the row label exists in the DataFrame's index before accessing it.
Python
import pandas as pd
df = pd.DataFrame({' Name': ['Alice', 'Bob'], 'Age': [25, 30]})
print(df.index)
if 'c' in df.index:
print(df.loc['c'])
else:
print("Row label not exist.")
OutputRangeIndex(start=0, stop=2, step=1)
Row label not exist.
Explanation: It first prints all row labels using df.index. Then, it uses the in operator to see if the label 'c' is present. If the label exists, it prints the corresponding row otherwise, it shows the message "Row label not exist.".
4. Multiple columns access with at least one missing
If you try to access multiple columns at once (e.g., df[['Name', 'Gender']]) and even one of them is missing, pandas will throw a KeyError.
Python
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob']}, index=['a', 'b'])
df[['Name', 'Gender']]
Output
KeyError: "['Gender'] not in index"
Solution: Filter out any columns that don't exist before accessing them.
Python
import pandas as pd
df = pd.DataFrame({'Name': ['Alice', 'Bob']}, index=['a', 'b'])
cols = [col for col in ['Name', 'Gender'] if col in df.columns]
df[cols]
Output
Explanation: It creates a list cols that includes only the column names that actually exist in the DataFrame by checking each desired column with the in operator. Then, it accesses and prints only those existing columns, avoiding a KeyError caused by missing columns like 'Gender'.
5. Case sensitivity
Pandas column names are case-sensitive. Trying to access df['name'] when the actual column is Name will result in a KeyError.
Python
import pandas as pd
df = pd.DataFrame({'Name': ['Alice']})
df['name']
Output
KeyError: 'name'
Solution: Convert all column names to lowercase (or uppercase) using .str.lower() for consistent access.
Python
import pandas as pd
df = pd.DataFrame({'Name': ['Alice']})
df['Name']
df.columns = df.columns.str.lower()
df['name']
Output
Using lower()Explanation: Initially, it accesses the column 'Name' with the exact case. Then, it converts all column names to lowercase using str.lower(), allowing you to access the same column using the lowercase name 'name' without causing a KeyError.
Related Articles
Similar Reads
How to Fix: No module named pandas
In this article, we will discuss how to fix the No module named pandas error. The error "No module named pandas " will occur when there is no pandas library in your environment IE the pandas module is either not installed or there is an issue while downloading the module right. Let's see the error b
2 min read
How to Learn Pandas ?
Pandas simplify complex data operations, allowing you to handle large datasets with ease, transform raw data into meaningful insights, and perform a wide range of data analysis tasks with minimal code. Whether you're new to programming or an experienced developer looking to enhance your data analysi
8 min read
How to solve pywhatkit KeyError in python?
If you come across a KeyError when working with pywhatkit - a popular Python library for automating tasks like sending Whatsapp messages, playing Youtube videos, or searching Google - it means that you are trying to look up a key that does not exist in a particular dictionary. The article contains a
3 min read
How to handle KeyError Exception in Python
In this article, we will learn how to handle KeyError exceptions in Python programming language. What are Exceptions?It is an unwanted event, which occurs during the execution of the program and actually halts the normal flow of execution of the instructions.Exceptions are runtime errors because, th
3 min read
How to Fix: NameError name âpdâ is not defined
In this article we will discuss how to fix NameError pd is not defined in Python. When we imported pandas module without alias and used pd in the code, the error comes up. Example: Code to depict error Python3 # import pandas module import pandas # create dataframe data = pd.DataFrame({'a': [1, 2],
2 min read
How to Flatten MultiIndex in Pandas?
In this article, we will discuss how to flatten multiIndex in pandas. Flatten all levels of MultiIndex: In this method, we are going to flat all levels of the dataframe by using the reset_index() function. Syntax: dataframe.reset_index(inplace=True) Note: Dataframe is the input dataframe, we have to
3 min read
How to Merge Two Pandas DataFrames on Index
Merging two pandas DataFrames on their index is necessary when working with datasets that share the same row identifiers but have different columns. The core idea is to align the rows of both DataFrames based on their indices, combining the respective columns into one unified DataFrame. To merge two
3 min read
How to Drop Index Column in Pandas?
When working with Pandas DataFrames, it's common to reset or remove custom indexing, especially after filtering or modifying rows. Dropping the index is useful when:We no longer need a custom index.We want to restore default integer indexing (0, 1, 2, ...).We're preparing data for exports or transfo
2 min read
How to Join Pandas DataFrames using Merge?
Joining and merging DataFrames is that the core process to start  out with data analysis and machine learning tasks. It's one of the toolkits which each Data Analyst or Data Scientist should master because in most cases data comes from multiple sources and files. In this tutorial, you'll how to join
3 min read
How to Fix - KeyError in Python â How to Fix Dictionary Error
Python is a versatile and powerful programming language known for its simplicity and readability. However, like any other language, it comes with its own set of errors and exceptions. One common error that Python developers often encounter is the "KeyError". In this article, we will explore what a K
5 min read