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.
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
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">![]()
<span class="hidden md:block">Watch a video course</span>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
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
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
if df.isnull().any().any():
print("Dataframe contains NaN values")
else:
print("Dataframe contains no NaN values")