Skip to main content
Albero Academy

Missing Data: NaN & Infinity

Handle the special floating-point values — detect NaN, aggregate around it with nan-aware functions, and clean data safely.

Chapter 8NumPy14 min readBeginner friendly
  • #NumPy
  • #NaN
  • #Data Cleaning

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:

the surprising rules
np.nan == np.nan # False (!) — never compare with ==
np.nan + 5 # nan — it poisons arithmetic
np.array([1, 2, np.nan]).sum() # nan — one NaN spoils the total
np.inf > 1e308 # True
1 / np.array([0.0]) # inf (with a warning), not an error

Detecting them

Because == fails, you must use the dedicated predicates:

finding the holes
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:

NormalNaN-skipping
np.sumnp.nansum
np.meannp.nanmean
np.max / np.minnp.nanmax / np.nanmin
np.stdnp.nanstd
summarise around the holes
a = np.array([10, np.nan, 30, 50])
a.mean() # nan
np.nanmean(a) # 30.0 ← ignores the NaN

Cleaning & replacing

fill or drop
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 entirely
clean = a[~np.isnan(a)]
# nan_to_num replaces NaN→0 and ±inf→large finite numbers
np.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

  1. 01np.nan is a float that is not equal to anything (even itself) and poisons plain arithmetic.
  2. 02Detect special values with np.isnan / np.isinf / np.isfinite — never with ==.
  3. 03The nan* functions (nanmean, nansum, nanmax…) skip missing values when aggregating.
  4. 04Clean by masking (a[~np.isnan(a)]), imputing (fill with nanmean), or np.nan_to_num.
  5. 05These NaN rules underlie missing-data behaviour throughout pandas and the wider stack.