How to Check if Cell Value is NaN in Pandas?
Check if Cell Value is NaN in Pandas
In this tutorial, we will learn how to check if a cell value is NaN (np.nan) in Pandas.
NaN means Not a Number. Pandas uses numpy.nan as NaN value.
To check if value at a specific location in Pandas is NaN or not, call numpy.isnan() function with the value passed as argument.
numpy.isnan(value)
If value equals numpy.nan, the expression returns True, else it returns False.
Examples
1. Check if a cell value is NaN in DataFrame
In this example, we will take a DataFrame with NaN values at some locations. We will check if values at specific locations are NaN or not.
Python Program
import pandas as pd
import numpy as np
df = pd.DataFrame(
[[np.nan, 72, 67],
[23, 78, 62],
[32, 74, np.nan],
[np.nan, 54, 76]],
columns=['a', 'b', 'c'])
value = df.at[0, 'a'] #nan
isNaN = np.isnan(value)
print("Is value at df[0, 'a'] NaN :", isNaN)
value = df.at[0, 'b'] #72
isNaN = np.isnan(value)
print("Is value at df[0, 'b'] NaN :", isNaN)
Output
Is value at df[0, 'a'] NaN : True
Is value at df[0, 'b'] NaN : False
2. Check if a cell value is NaN in DataFrame iteratively
In this example, we will take a DataFrame with NaN values at some locations. We will iterate over each of the cell values in this DataFrame and check if the value at this location is NaN or not.
Python Program
import pandas as pd
import numpy as np
df = pd.DataFrame(
[[np.nan, 72, 67],
[23, 78, 62],
[32, 74, np.nan],
[np.nan, 54, 76]])
for i in range(df.shape[0]): #iterate over rows
for j in range(df.shape[1]): #iterate over columns
value = df.at[i, j] #get cell value
print(np.isnan(value), end="\t")
print()
Output
True False False
False False False
False False True
True False False
Summary
In this tutorial of Python Examples, we learned how to check if a specific cell value in Pandas is NaN or not using numpy.isnan() function.