For a single Python floating-point value, call math.isnan(x). Do not use x == float("nan") or x is math.nan: NaN is unequal to every value, including itself, and Python’s documentation recommends isnan() for the test.
Check a Python float with math.isnan()
import math
x = float("nan")
if math.isnan(x):
print("x is NaN")
math.isnan(x) returns a Boolean indicating whether the number is NaN. The Python math documentation explicitly advises using isnan() rather than is or == for this check.
Why equality and identity checks fail
NaN is not equal to itself. Consequently, x == float("nan") is false even when x is NaN. Identity is not a reliable substitute: x is math.nan checks whether two references point to the same object, not whether a value is NaN.
import math
x = float("nan")
print(x == float("nan")) # False
print(math.isnan(x)) # True
Choose the test for your data and goal
| Input or goal | Use | What it returns or detects |
|---|---|---|
| Python numeric scalar; NaN only | math.isnan(x) |
One Boolean indicating whether the value is NaN. |
| Python number; reject NaN and either infinity | math.isfinite(x) |
True for finite numbers, including zero; false for NaN and positive or negative infinity. |
| NumPy scalar or array; NaN only | numpy.isnan(x) |
A scalar Boolean for scalar input or an element-wise Boolean array for array input. |
| pandas data; general missing-value check | Series.isna() or pandas.notna(x) |
Missing-data results, not a NaN-only test. notna reports whether values are present. |
For NumPy arrays, create an element-wise mask
Use numpy.isnan() when the input is a NumPy array and you need to test each element. The result has a Boolean for each array element; for scalar input, it returns a scalar Boolean. NumPy treats NaN and infinity as distinct, so this is not an all-non-finite-values check. See the NumPy isnan reference.
#1 Best Overall
For pandas, test for missing data
pandas’ isna() and notna() use missing-data semantics, which are broader than checking whether a floating-point value is NaN. For a Series, call series.isna(); for scalar or array-like input, pandas.notna(x) returns validity results. pandas recognizes values such as None, NaN, and NaT as missing, but an empty string and numpy.inf are not considered NA by Series.isna().
import pandas as pd
missing_mask = series.isna()
valid_mask = pd.notna(series)
Consult the pandas references for Series.isna() and pandas.notna() when choosing the behavior you want.
Quick Recap
Best Value
Rank #2
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




