NaN and inf (NumPy)
np.nan represents a missing or undefined floating-point value ('Not a Number'), and np.inf represents infinity. Both arise from floating-point math and need special functions like np.isnan and np.isinf to detect.
NumPy
NaN appears from undefined operations like 0/0 and as a placeholder for missing data; inf appears from overflow or division by a nonzero number by zero. Both are valid float64 values, so a single one can silently propagate through a calculation.
You cannot test for NaN with ==, because NaN compares unequal to everything including itself; use np.isnan(a) to find it and np.isinf(a) for infinities, or np.isfinite(a) to mark the 'normal' values. Regular reductions like sum and mean return NaN if any element is NaN.
To compute despite missing values, the nan-aware functions np.nansum, np.nanmean, and np.nanstd skip NaNs, and np.nan_to_num replaces NaN and inf with finite substitutes.
Syntax
np.isnan(a) | np.isinf(a) | np.nanmean(a)Examples
Python
import numpy as np
print(np.isnan(np.array([1, np.nan, 3])))Output:
[False True False]