How to Check for Nan Values

Better Stack Team
Updated on June 19, 2024

In pandas, you can check for NaN (Not a Number) values using the isna() or isnull() methods. These methods return a DataFrame of the same shape as the original DataFrame, where each element is True if it's NaN and False otherwise. Here's how you can do it:

 
import pandas as pd
import numpy as np

# Create a DataFrame with NaN values
data = {'A': [1, np.nan, 3], 'B': [np.nan, 5, np.nan], 'C': [7, 8, 9]}
df = pd.DataFrame(data)

# Check for NaN values using isna()
nan_values = df.isna()

print("DataFrame:")
print(df)
print("\\nNaN values:")
print(nan_values)

This will output:

 
DataFrame:
     A    B  C
0  1.0  NaN  7
1  NaN  5.0  8
2  3.0  NaN  9

NaN values:
       A      B      C
0  False   True  False
1   True  False  False
2  False   True  False

In this example, nan_values is a DataFrame where each True value indicates a NaN value in the corresponding position of the original DataFrame df.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.