DS Handling Missing Data
Real datasets have holes. Riverside Bikes' weather station loses its connection, a rental terminal crashes, someone forgets to fill in a form. How you handle missing values can change your results — sometimes more than the choice of model.
Finding missing values
pandas represents missing values as NaN (or None/NaT for objects and dates). isna() marks them; summing counts them per column. Let's damage a copy of the dataset the way a flaky sensor would:
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
holes = bikes.copy()
gap = np.random.default_rng(1)
holes.loc[gap.choice(60, 8, replace=False), "temp_c"] = np.nan
holes.loc[gap.choice(60, 5, replace=False), "rain_mm"] = np.nan
print(holes.isna().sum())
print()
print("Share of complete rows:", holes.notna().all(axis=1).mean().round(3))
print(holes[holes["temp_c"].isna()].head(3))date 0
temp_c 8
rain_mm 5
humidity 0
weekend 0
rides 0
dtype: int64
Share of complete rows: 0.8
date temp_c rain_mm humidity weekend rides
1 2024-04-02 NaN NaN 88 0 298
8 2024-04-09 NaN 2.4 36 0 209
25 2024-04-26 NaN 4.7 42 0 204
13 missing cells don't sound like much, but they affect a larger share of rows, and many methods drop any row with a single gap.
Why values are missing matters
| Mechanism | Meaning | Example | Risk of dropping rows |
|---|---|---|---|
| MCAR — missing completely at random | Gaps are unrelated to anything | Random network outages | Lose data, but no bias |
| MAR — missing at random | Gaps depend on other observed variables | Sensor fails more often on weekends | Bias unless you account for that variable |
| MNAR — missing not at random | Gaps depend on the missing value itself | Rain gauge overflows on the heaviest downpours | Biased; no simple fix |
Before choosing a method, ask why the values are missing. A gauge that fails on the wettest days would make the remaining data look drier than reality, and no amount of clever filling recovers that.
Strategy 1: drop
dropna() removes rows (or columns) with missing values. Simple and honest when gaps are few and random:
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
holes = bikes.copy()
gap = np.random.default_rng(1)
holes.loc[gap.choice(60, 8, replace=False), "temp_c"] = np.nan
holes.loc[gap.choice(60, 5, replace=False), "rain_mm"] = np.nan
print("all rows: ", len(holes))
print("dropna(): ", len(holes.dropna()))
print("dropna(subset=temp): ", len(holes.dropna(subset=["temp_c"])))
print("dropna(thresh=6): ", len(holes.dropna(thresh=6))) # keep rows with >= 6 non-missingall rows: 60
dropna(): 48
dropna(subset=temp): 52
dropna(thresh=6): 48
Strategy 2: fill (impute)
Imputation replaces gaps with plausible values. Choose the rule per column, based on what the column means:
| Method | Good for | pandas |
|---|---|---|
| A constant | Values that are missing because they're zero (no rain recorded) | fillna(0) |
| Mean / median | Roughly random gaps in a numeric column | fillna(s.median()) |
| Group median | Gaps where groups differ (weekday vs weekend) | groupby(...).transform("median") |
| Previous / next value | Slowly changing time series | ffill(), bfill() |
| Interpolation | Smooth time series | interpolate() |
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
dates = pd.date_range("2024-04-01", periods=60)
temp = rng.uniform(4, 30, 60).round(1)
rain = np.where(rng.random(60) < 0.3, rng.uniform(1, 15, 60), 0).round(1)
humidity = rng.integers(35, 95, 60)
weekend = (dates.dayofweek >= 5).astype(int)
rides = (150 + 12 * temp - 8 * rain + 60 * weekend + rng.normal(0, 30, 60)).round().astype(int)
bikes = pd.DataFrame({"date": dates, "temp_c": temp, "rain_mm": rain,
"humidity": humidity, "weekend": weekend, "rides": rides})
holes = bikes.copy()
gap = np.random.default_rng(1)
missing_rows = gap.choice(60, 8, replace=False)
holes.loc[missing_rows, "temp_c"] = np.nan
truth = bikes.loc[missing_rows, "temp_c"]
options = {
"mean": holes["temp_c"].fillna(holes["temp_c"].mean()),
"ffill": holes["temp_c"].ffill(),
"interpolate": holes["temp_c"].interpolate(),
}
for name, filled in options.items():
err = (filled[missing_rows] - truth).abs().mean()
print(f"{name:12} mean abs error on the gaps: {err:.2f} °C")
print()
print("std before:", round(bikes["temp_c"].std(), 2),
"| std after mean-fill:", round(options["mean"].std(), 2))mean mean abs error on the gaps: 6.44 °C
ffill mean abs error on the gaps: 10.49 °C
interpolate mean abs error on the gaps: 8.41 °C
std before: 7.37 | std after mean-fill: 6.85
Because we know the true values, we can score each method. Here the simple mean fill happens to do best: our simulated daily temperatures jump randomly from day to day, so a neighbouring day carries no extra information. For real weather, which changes gradually, interpolation usually wins — always think about how the data behaves.
The last line shows a side effect: filling with the mean shrinks the standard deviation, because every filled value sits exactly at the centre. Imputed data looks more certain than it is.
Strategy 3: flag
Whatever you fill, keep a record. A boolean indicator column lets you check later whether filled rows behave differently, and lets a model learn from the fact that a value was missing:
import numpy as np
import pandas as pd
df = pd.DataFrame({"temp_c": [24.1, np.nan, 26.3, np.nan, 6.4],
"rides": [414, 298, 439, 405, 254]})
df["temp_missing"] = df["temp_c"].isna()
df["temp_c"] = df["temp_c"].fillna(df["temp_c"].median())
print(df) temp_c rides temp_missing
0 24.1 414 False
1 24.1 298 True
2 26.3 439 False
3 24.1 405 True
4 6.4 254 False
Tip: Document every rule: "8 missing temperatures (13 %) filled with the mean; results unchanged when those days are dropped." Re-running the analysis both ways is the simplest robustness check.
Test yourself
Which call counts missing values per column?
df.count_na()df.isna().sum()df.dropna().sum()df.null()
A rain gauge fails mostly during the heaviest rain. Which mechanism is this?
- MCAR
- MAR
- MNAR
- Not missing data
What is a side effect of filling gaps with the mean?
- The mean changes a lot
- The standard deviation is underestimated
- The data gets more rows
- Correlations become exactly 1