Skip to content

How to check if any value is NaN in a Pandas DataFrame โ€‹

You can use the isna() method to check for NaN values in a Pandas DataFrame. The method returns a DataFrame of the same shape as the original, but with True or False values indicating whether each element is NaN or not. Here is an example code snippet:

Check if any value is NaN in a Pandas DataFrame in Python

python
import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3, 4, float('nan')],
    'B': [float('nan'), 2, 3, 4, 5],
    'C': [1, 2, float('nan'), 4, 5]
})

# Check for NaN values
nan_mask = df.isna()

# Print the result
print(nan_mask)

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

You can also use isnull() method for the same purpose

Check if any value is NaN in a Pandas DataFrame in Python using the isnull method

python
nan_mask = df.isnull()

You can also use the following code snippet to check if any value is NaN in the DataFrame:

Check if any value is NaN in a Pandas DataFrame in Python using the isna and any methods

python
if df.isna().any().any():
    print("Dataframe contains NaN values")
else:
    print("Dataframe contains no NaN values")

or

Check if any value is NaN in a Pandas DataFrame in Python using the isnull and any methods

python
if df.isnull().any().any():
    print("Dataframe contains NaN values")
else:
    print("Dataframe contains no NaN values")

Dual-run preview โ€” compare with live Symfony routes.