← chapter

Missing values and messy data

Find and fix the problems in real data before any model runs.

A missing value doesn't have to be blank to be missing. Sometimes it's a zero hiding in plain sight.

The Pima trap

Your data is dirtier than you think

652 disguised-missing cells in the "clean" Pima benchmark. Insulin is 48.7% fake.

The math

Fill with the mean or the median of the observed values:

xˉ=1ni=1nximedian(x)=x((n+1)/2)\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i \qquad \operatorname{median}(x) = x_{((n+1)/2)}

Two outlier rules that disagree on purpose:

z-score: flag xixˉ/σ>3\text{z-score: flag } |x_i - \bar{x}| / \sigma > 3 IQR: flag xi<Q11.5IQR   or   xi>Q3+1.5IQR\text{IQR: flag } x_i < Q_1 - 1.5\,\text{IQR} \;\text{ or }\; x_i > Q_3 + 1.5\,\text{IQR}

The z-score's mean and std are inflated by the very outliers it hunts, so it under-flags a skewed column. IQR doesn't.

Detect the disguised zeros

Real NaNs, plus zeros in the columns where zero is physically impossible.

Mean sits high, median lands in the bulk

Insulin is 48.7% fake zeros and right-skewed. Mean fill parks at 156 in the empty tail; median fill lands at 125 in the bulk.

Cleaning is not a button

Fixed classifier, one split. Test accuracy — fraction of 192 held-out patients called right (unitless, 0–1).

Raw zeros 0.781, naive impute drops to 0.750 — the missingness was informative. Median + a was-missing flag recovers it: 0.771.

Takeaways