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
Selected Reading
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.
Advertisements
