KeyError
in PandasThe KeyError
in Pandas occurs when you try to access a column, row, or key that doesn’t exist in the DataFrame or Series. This article explains the common causes of KeyError
and provides practical solutions to avoid or handle it effectively.
KeyError
import pandas as pd
# Example DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# Attempt to access a non-existent column
print(df['Score']) # Triggers KeyError
Output:
KeyError: 'Score'
# Attempt to access a non-existent row label
print(df.loc[3]) # Triggers KeyError
Output:
KeyError: 3
KeyError
in Pandasin
or .get()
to Check for Column ExistenceBefore accessing a column, check if it exists using the in
keyword or the get()
method.
# Check column existence
if 'Score' in df.columns:
print(df['Score'])
else:
print("Column 'Score' does not exist")
Output:
Column 'Score' does not exist
.get()
for Safe Access in SeriesThe .get()
method returns None
or a default value if the key is not found.
# Create a Series
s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
# Safely access a non-existent key
print(s.get('d', 'Key not found'))
Output:
Key not found
try-except
to Handle KeyError
Wrap the code in a try-except
block to handle the error gracefully.
try:
print(df['Score'])
except KeyError as e:
print(f"KeyError: {e}")
Output:
KeyError: 'Score'
.reindex()
to Handle Missing Index LabelsWhen working with specific indices, use .reindex()
to fill missing labels.
# Reindex the DataFrame
df_reindexed = df.reindex([0, 1, 2, 3], fill_value="Not Found")
print(df_reindexed)
Output:
Name Age
0 Alice 25.0
1 Bob 30.0
2 Charlie 35.0
3 Not Found NaN
KeyError
.get()
or in
checks for safe access.try-except
blocks for robust error handling.fill_value
to handle missing labels gracefully.The KeyError
in Pandas is a common issue, but it’s easy to prevent and handle with the right practices. By checking for existence, using safe access methods, and applying robust error-handling strategies, you can work with Pandas DataFrames and Series more effectively.
Pandas: How to Access Columns by Name In Pandas, accessing columns by name is a…
Pandas: How to Access or Select Columns by Index, not by Name In Pandas, accessing…
Pandas: How to Access Row by Index In Pandas, you can access rows in a…
Pandas: How to Access a Column Using iterrows() In Pandas, iterrows() is commonly used to…
Pandas - How to Update Values in iterrows In Pandas, iterrows() is a popular method…
Pandas KeyError When Using iterrows() In Pandas, the iterrows() method is often used to iterate…