Real datasets have holes — a missing reading, a divide-by-zero. NumPy represents "not a number" as np.nan and overflow as np.inf. They behave surprisingly, so knowing how to detect and handle them is essential hygiene.
The surprising rules
np.nan == np.nan # False (!) — never compare with ==np.array([1, 2, np.nan]).sum() # nan — one NaN spoils the total
Detecting & aggregating
Because == fails, use the predicates — and the nan* functions that skip missing values:
a = np.array([10, np.nan, 30, 50])np.isnan(a) # [False True False False]np.isnan(a).sum() # 1 — how many are missingnp.nanmean(a) # 30.0 — mean ignoring NaN (a.mean() would be nan)
Cleaning
clean = a[~np.isnan(a)] # drop the NaNsa[np.isnan(a)] = np.nanmean(a) # or impute with the mean
Key takeaways
- 01np.nan is a float that is not equal to anything (even itself) and poisons plain aggregations.
- 02Detect it with np.isnan (never ==); count missing with np.isnan(a).sum().
- 03The nan* functions (nanmean, nansum, nanmax) skip missing values.
- 04Clean by masking (a[~np.isnan(a)]) or imputing (fill with nanmean).
