Python Pandas - Check if the index has NaNs



To check if the index has NaNs, use the index.hasnans property in Pandas.

At first, import the required libraries −

import pandas as pd import numpy as np

Creating the index. For NaN, we have used numpy library −

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

Display the index −

print("Pandas Index...\n",index)

Check if the index is having NaNs −

print("\nIs the Pandas index having NaNs?\n",index.hasnans) 

Example

Following is the code −

import pandas as pd import numpy as np # Creating the index # For NaN, we have used numpy library index = pd.Index(['Car','Bike', np.nan,'Car',np.nan, 'Ship']) # Display the index print("Pandas Index...\n",index) # Return an array representing the data in the Index print("\nArray...\n",index.values) # Check if the index is having NaNs print("\nIs the Pandas index having NaNs?\n",index.hasnans) # Return a tuple of the shape of the underlying data print("\nA tuple of the shape of underlying data...\n",index.shape)

Output

This will produce the following code −

Pandas Index... Index(['Car', 'Bike', nan, 'Car', nan, 'Ship'], dtype='object') Array... ['Car' 'Bike' nan 'Car' nan 'Ship'] Is the Pandas index having NaNs? True A tuple of the shape of underlying data... (6,)
Updated on: 2021-10-13T11:14:33+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements