Skip to main content
Albero Academy

Missing Data (NaN)

Detect and handle NaN and infinity — essential data-cleaning hygiene.

Numerical Computing9 min

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

NaN breaks equality and poisons sums
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:

isnan and nan-aware functions
a = np.array([10, np.nan, 30, 50])
np.isnan(a) # [False True False False]
np.isnan(a).sum() # 1 — how many are missing
np.nanmean(a) # 30.0 — mean ignoring NaN (a.mean() would be nan)

Cleaning

drop or fill
clean = a[~np.isnan(a)] # drop the NaNs
a[np.isnan(a)] = np.nanmean(a) # or impute with the mean

Key takeaways

  1. 01np.nan is a float that is not equal to anything (even itself) and poisons plain aggregations.
  2. 02Detect it with np.isnan (never ==); count missing with np.isnan(a).sum().
  3. 03The nan* functions (nanmean, nansum, nanmax) skip missing values.
  4. 04Clean by masking (a[~np.isnan(a)]) or imputing (fill with nanmean).

Finished this chapter?

Mark it complete to track your progress through NumPy.