Real datasets have holes — a missing reading, a failed sensor, a divide-by-zero. NumPy represents "not a number" as np.nan and overflow as np.inf. They behave in surprising ways, so knowing how to detect and handle them is essential data-cleaning hygiene.
NaN and infinity
np.nan is a float, so any array containing it is a float array. Its defining quirk: it's not equal to anything, even itself:
np.nan == np.nan # False (!) — never compare with ==np.nan + 5 # nan — it poisons arithmeticnp.array([1, 2, np.nan]).sum() # nan — one NaN spoils the totalnp.inf > 1e308 # True1 / np.array([0.0]) # inf (with a warning), not an error
Detecting them
Because == fails, you must use the dedicated predicates:
a = np.array([1.0, np.nan, 3.0, np.inf])np.isnan(a) # [False True False False]np.isinf(a) # [False False False True]np.isfinite(a) # [ True False True False]np.isnan(a).sum() # 1 → how many missing values
nan-aware aggregation
The nan* family skips missing values instead of returning NaN — the safe way to summarise dirty data:
| Normal | NaN-skipping |
|---|---|
np.sum | np.nansum |
np.mean | np.nanmean |
np.max / np.min | np.nanmax / np.nanmin |
np.std | np.nanstd |
a = np.array([10, np.nan, 30, 50])a.mean() # nannp.nanmean(a) # 30.0 ← ignores the NaN
Cleaning & replacing
a = np.array([10, np.nan, 30])# Replace NaN with the column mean (a simple imputation)a[np.isnan(a)] = np.nanmean(a)# Or drop them entirelyclean = a[~np.isnan(a)]# nan_to_num replaces NaN→0 and ±inf→large finite numbersnp.nan_to_num(np.array([np.nan, np.inf, 1.0]))
Practice
Make an array with a few np.nan values. Count them with np.isnan, compute a correct mean with np.nanmean, then produce two cleaned versions — one dropping the NaNs, one imputing them with the mean.
Key takeaways
- 01np.nan is a float that is not equal to anything (even itself) and poisons plain arithmetic.
- 02Detect special values with np.isnan / np.isinf / np.isfinite — never with ==.
- 03The nan* functions (nanmean, nansum, nanmax…) skip missing values when aggregating.
- 04Clean by masking (a[~np.isnan(a)]), imputing (fill with nanmean), or np.nan_to_num.
- 05These NaN rules underlie missing-data behaviour throughout pandas and the wider stack.
