How to Check for Nan Values
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
.
Make your mark
Join the writer's program
Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.
Write for usBuild on top of Better Stack
Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.
community@betterstack.comor submit a pull request and help us build better products for everyone.
See the full list of amazing projects on github