Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What happens if the specified index is not present in the series Python Pandas?
When accessing pandas Series elements using custom index values, you use the syntax series_name['index_value']. If the specified index exists, the corresponding data is returned. However, if the index is not present in the series, pandas raises a KeyError.
Example: Accessing Non-existent Index
Let's see what happens when we try to access an index that doesn't exist ?
import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
print("The series contains following elements:")
print(my_series)
print("\nAttempting to access non-existent index 'mm':")
print(my_series['mm'])
The output shows the series data and then raises a KeyError ?
The series contains following elements: ab 34 mn 56 gh 78 kl 90 wq 123 az 45 dtype: int64 Attempting to access non-existent index 'mm': Traceback (most recent call last): KeyError: 'mm'
Safe Methods to Handle Missing Index
Using get() Method
The get() method returns None for missing keys instead of raising an error ?
import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
# Safe access using get()
result = my_series.get('mm')
print(f"Value for 'mm': {result}")
# With default value
result = my_series.get('mm', 'Index not found')
print(f"Value for 'mm' with default: {result}")
Value for 'mm': None Value for 'mm' with default: Index not found
Using try-except Block
Handle the KeyError explicitly using exception handling ?
import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
try:
value = my_series['mm']
print(f"Value found: {value}")
except KeyError:
print("Index 'mm' not found in the series")
Index 'mm' not found in the series
Checking Index Existence
You can check if an index exists before accessing it ?
import pandas as pd
my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)
# Check if index exists
if 'mm' in my_series.index:
print(f"Value: {my_series['mm']}")
else:
print("Index 'mm' does not exist")
# Check existing index
if 'ab' in my_series.index:
print(f"Value for 'ab': {my_series['ab']}")
Index 'mm' does not exist Value for 'ab': 34
Comparison of Methods
| Method | Behavior on Missing Index | Best For |
|---|---|---|
series['key'] |
Raises KeyError | When index must exist |
series.get('key') |
Returns None | Safe access with default |
try-except |
Custom error handling | Complex error handling |
'key' in series.index |
Returns False | Checking existence first |
Conclusion
When a specified index is not present in a pandas Series, accessing it directly raises a KeyError. Use get() method for safe access or check index existence with in operator to handle missing indices gracefully.
