Module 10 · Feature Engineering: Making Data Model-Ready · Lesson 33 of 51
Missing values, outliers and leakage
Ways to fill gaps and flag them, handling outliers, the train/test rule for every transform, and data leakage: the mistake that makes models look brilliant and fail in real life.
In this lesson · about 40 minutes
- Impute missing values and add a missing-indicator feature
- Cap outliers sensibly instead of deleting rows blindly
- Spot target leakage and fit every transform on training data only
Missing values
| Approach | When |
|---|---|
| Drop the rows | Very few rows are missing and they're missing at random. |
| Fill with median (numbers) or most common value (categories) | The usual default. Median resists outliers. |
| Fill with a group value (median spend per branch) | When groups differ a lot. |
| Add a "was missing" flag | Often: missingness itself can predict the target (people who skip "phone number" behave differently). |
Outliers
First ask: is it an error (an age of 420) or real but rare (a $900 catering order)? Fix or remove errors. For real extremes, cap ("winsorise") at a percentile like the 1st and 99th, or use a log transform, rather than deleting customers who really exist.
The golden rule: fit on train, apply to test
The median you fill with, the mean and std you scale with, the categories you one-hot: all must be learned from the training rows only, then applied unchanged to the test rows. Otherwise test information leaks into training. Scikit-learn's pipelines (Module 12) do this automatically.
Kinds of leakage
- Target leakage: a feature only known after the outcome. "Cancellation reason" predicting churn; "refund issued" predicting fraud.
- Time leakage: using next month's data to predict this month. Split by time when the model will predict the future.
- Duplicate leakage: the same customer in train and test, so the model just remembers them.
Imputing with a flag, and capping
Exercise
Fill from the training rows only
The rows are already split into train and test, and some avg_spend values are missing. Compute the training median as med (rounded to 2 decimals), fill the gaps in both tables with it, and add a column spend_missing (1 if it was missing, else 0) to both, before filling. Finally set result to (med, int(test["spend_missing"].sum()), round(float(test["avg_spend"].mean()), 3)).
Code that runs before yours
import pandas as pd
import numpy as np
members = pd.read_csv("kc_members.csv")
rng = np.random.default_rng(3)
members.loc[rng.random(len(members)) < 0.1, "avg_spend"] = np.nan
train = members.iloc[:600].copy()
test = members.iloc[600:].copy()Sorting drill
Leak or fine?
You're predicting whether a member will churn next month. Which features are safe to use?
- Visits in the last 90 days
- Date the member cancelled
- Complaints filed so far
- Whether they received the 'sorry to see you go' email
- Tenure in months
- Visits next month
0 of 6 sorted
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 1
Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.