Python Pandas - Check if the index has NaNs

To check if a Pandas index contains NaN values, use the hasnans property. This boolean property returns True if any NaN values are present in the index.

Syntax

index.hasnans

Creating an Index with NaN Values

First, let's create an index that contains some NaN values ?

import pandas as pd
import numpy as np

# Creating an index with NaN values
index = pd.Index(['Car', 'Bike', np.nan, 'Car', np.nan, 'Ship'])
print("Pandas Index...")
print(index)
Pandas Index...
Index(['Car', 'Bike', nan, 'Car', nan, 'Ship'], dtype='object')

Checking for NaN Values

Use the hasnans property to check if the index contains any NaN values ?

import pandas as pd
import numpy as np

index = pd.Index(['Car', 'Bike', np.nan, 'Car', np.nan, 'Ship'])

# Check if the index has NaN values
print("Does the index have NaN values?", index.hasnans)

# Display the underlying array
print("\nUnderlying array:")
print(index.values)

# Get the shape of the index
print("\nShape of the index:", index.shape)
Does the index have NaN values? True

Underlying array:
['Car' 'Bike' nan 'Car' nan 'Ship']

Shape of the index: (6,)

Comparing Index with and without NaN

Let's compare the behavior of hasnans for indexes with and without NaN values ?

import pandas as pd
import numpy as np

# Index with NaN values
index_with_nan = pd.Index(['Car', 'Bike', np.nan, 'Ship'])
print("Index with NaN:", index_with_nan.hasnans)

# Index without NaN values
index_without_nan = pd.Index(['Car', 'Bike', 'Truck', 'Ship'])
print("Index without NaN:", index_without_nan.hasnans)
Index with NaN: True
Index without NaN: False

Conclusion

The hasnans property provides a quick way to check if a Pandas index contains NaN values. It returns True if any NaN values are present and False otherwise.

Updated on: 2026-03-26T16:13:31+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements