Here are the five ways to check for a NaN (Not a Number) values in Python:
- Using math.isnan()
- Using numpy.isnan()
- Using pandas.isna()
- Checking the range
- Using comparisons(not recommended)
Method 1: Using math.isnan()
When working with a float value, you can use math.isnan() .
This function checks whether a value is NaN, returning True if the specified value is NaN; otherwise, it returns False.
Visual Representation
Example
import math
value1 = 2.28
value2 = float("nan")
print(math.isnan(value1))
print(math.isnan(value2))
Output
False
True
Method 2: Using numpy.isnan()
In NumPy and Pandas, NaN is used to represent missing numerical data.
NumPy has a function isnan() that checks for NaN in arrays and scalars. It returns the result as a boolean array.
Visual Representation
Example
import numpy as np
# Create a NumPy array with both float values and NaN values
my_array = np.array([2.28, np.nan, np.nan, 4.67])
# Use np.isnan() to check each element of the array for NaN
array_is_nan = np.isnan(my_array)
print(array_is_nan)
# Check if a single value is NaN
value = np.nan
is_nan = np.isnan(value)
print(is_nan)
Output
[False True True False]
True
Method 3: Using pandas.isna()
Pandas provides functions like isna() or isnull() that are useful for checking NaN values in Series and DataFrames.
Visual Representation
Example
import pandas as pd
# Create a Pandas Series with both float values and NA (missing) values
my_df = pd.Series([2.28, pd.NA, pd.NA, 7])
# Use the isna() method to check each element in the Series for NA (missing) values
df_is_na = my_df.isna() # isnull() can also be used as it's an alias of isna()
print("Array: ", df_is_na)
# Check if a single value is NA
value = pd.NA
# Use pd.isna() to check if 'value' is NA
df_is_na = pd.isna(value)
print("Single Value:", df_is_na)
Output
Array:
0 False
1 True
2 True
3 False
dtype: bool
Single Value: True
Method 4: Checking the range
We can use the range property of NaN to check for NaN values.
All floating-point values fall within the range from negative infinity to positive infinity, denoted as -infinity < any number < infinity.
However, NaN values do not fall within this range. Therefore, NaN can be identified if a value does not lie within the range.
Example
def isNaN(num):
if float('-inf') < float(num) < float('inf'):
return False
else:
return True
value1 = 2.28
print(isNaN(value1))
value2 = float("nan")
print(isNaN(value2))
Output
False
True
Method 5: Using comparisons (not recommended)
Direct comparisons to NaN (value == np.nan or value != value) are not effective because NaN is not equal to anything, including itself.
NaN is recognized in the context of floating-point numbers, not as a string or other data type.
Example
def isNaN(num):
return num!= num
value1 = 2.28
print(isNaN(value1))
value2 = float("nan")
print(isNaN(value2))
Output
False
True