Q.What would happen if the label or row index passed is not present in the DataFrame?
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →When a label or row index that does not exist in a DataFrame is accessed, pandas raises a KeyError (for .loc[] or dictionary-style access) or an IndexError (for .iloc[] with out-of-range positions).
The behavior depends on which indexing method you use and what operation you're performing. Understanding this is crucial because DataFrames are labeled data structures — unlike lists where positions are always 0, 1, 2…, DataFrame indices can be arbitrary labels (strings, dates, integers that skip values). When you ask for a label that doesn't exist, pandas must decide: error out or return something safe.
Dictionary-style and .loc[] access: KeyError
When you use dictionary-style indexing (df['column']) for a column or .loc[] for a row label, pandas treats the DataFrame like a labeled mapping. If the label isn't found, it raises a KeyError.
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob', 'Charlie'],
'Score': [85, 90, 78]
}, index=['A', 'B', 'C'])
# Attempt to access a non-existent column
try:
print(df['Marks'])
except KeyError as e:
print(f"KeyError: {e}")
# Attempt to access a non-existent row label
try:
print(df.loc['D'])
except KeyError as e:
print(f"KeyError: {e}")
Output:
KeyError: 'Marks'
KeyError: 'D'
The error is immediate and explicit: the label you requested does not exist in the axis (columns or index).
Position-based .iloc[] access: IndexError
When you use .iloc[] (integer-location based), you're asking for the n-th row or column by position, just like a list. If the position is out of range, pandas raises an IndexError.
# DataFrame has 3 rows (positions 0, 1, 2)
try:
print(df.iloc[5])
except IndexError as e:
print(f"IndexError: {e}")
Output:
IndexError: single positional indexer is out-of-bounds
This is the same error you'd get from my_list[100] when the list has only 10 elements.
Safe alternatives: .get() and .reindex()
If you want to avoid exceptions and handle missing labels gracefully, pandas provides:
1. .get() for columns (returns None or a default)
result = df.get('Marks', default='Column not found')
print(result)
Output:
Column not found
2. .reindex() for rows (fills missing labels with NaN)
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.