Part 03 / Topic 3 of 6
Missing values
Real exports always have holes. Three honest options:
| Option | When |
|---|---|
| Drop rows | Few rows affected, data plentiful |
| Impute (median/mode) | Default — keeps the rows, simple to explain |
| Model-based imputation | Rarely worth it before trying simple |
The trap is not how to fill — it is where the fill value comes from. A median computed over all data includes the test rows, and knowledge of the test set has then leaked into training. Always: split first, then impute using training data only.
# examples/02_split_first_then_fill_missing_values.py
from sklearn.model_selection import train_test_split
from ailab import make_churn
df = make_churn()
train, test = train_test_split(df, test_size=0.2, random_state=42, stratify=df["churned"])
median = train["monthly_charges"].median() # learned from train only
train = train.assign(monthly_charges=train["monthly_charges"].fillna(median))
test = test.assign(monthly_charges=test["monthly_charges"].fillna(median))
print("train:", len(train), "test:", len(test))
print("churn rate train/test:", round(train.churned.mean(), 3), round(test.churned.mean(), 3))
print("median used for both:", median)
# train: 1600 test: 400
# churn rate train/test: 0.299 0.3
# median used for both: 70.185
🧪 Quick quiz
- Why fill missing values using statistics from the training split only?
Show the answer
Using test data would leak information about the test set into training. Anything learned from data — including an imputation median — must come from the training split, so the test score stays honest.
Done here? The practice set for Part 3 — 4 exercises with solutions — is on the part page.