Sub topic 4
Handling missing values
This chapter assumes you know basic pandas, scikit-learn's fit and transform workflow, and the leakage rule from the previous chapter: every statistic is learned from training data only.
Why missing values need a decision
Most scikit-learn estimators raise an error when the input contains NaN. Dropping rows or filling blanks without thought can also bias the model. The aim is to turn each gap into something the model can use, without leaking information and without hiding the fact that a value was absent.
Find out what "missing" looks like
Start by counting gaps per column. Then look for missing data that is not stored as NaN.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"age": [34, np.nan, 51, 29, -999],
"city": ["Oslo", "N/A", "Bergen", None, "Oslo"],
})
print(df.isna().mean()) # share of NaN per column
# Convert disguised missing values to real NaN
df = df.replace({"N/A": np.nan, -999: np.nan})
print(df.isna().sum())Sentinel values such as -999, 0, "unknown" or "N/A" are a common source of silent errors. An imputer only recognises NaN (or the value you set in missing_values), so a -999 would be treated as a real age and distort the mean.
Why the value is missing
The reason for the gap decides which treatment is safe. Statisticians use three categories.
| Mechanism | Meaning | Example | Consequence |
|---|---|---|---|
| MCAR (missing completely at random) | Missingness is unrelated to any value | A sensor drops packets at random | Dropping rows is unbiased, but wastes data |
| MAR (missing at random) | Missingness depends on other observed columns | Older customers skip the income field | Imputing from other columns works well |
| MNAR (missing not at random) | Missingness depends on the missing value itself | High earners hide their income | Imputation cannot recover the value. Keep a missingness flag |
You cannot prove which mechanism applies from the data alone. Use domain knowledge, and check whether the missing rate differs across groups or across the target.
Choosing a strategy
The diagram shows a typical decision path.
The 60 percent threshold is a rough guide, not a rule. A column that is 80 percent empty can still be useful if its presence predicts the target.
Dropping rows or columns
Dropping rows is acceptable when few rows are affected and the gaps look MCAR. In other cases it shrinks the data and can bias it. It also fails at serving time, because you cannot refuse to predict for a customer who has a blank field. Prefer imputation for any column the model will see in production.
Simple imputation
SimpleImputer replaces gaps with a statistic learned during fit.
| Strategy | Column type | Notes |
|---|---|---|
| `mean` | Numeric | Sensitive to outliers. Reasonable for symmetric data |
| `median` | Numeric | Robust default for skewed data such as income |
| `most_frequent` | Numeric or categorical | Can inflate the majority class |
| `constant` | Either | Use `fill_value="missing"` to make a new category |
For categorical columns, constant with an explicit label often works better than most_frequent. The model can then learn that "missing" behaves differently from every real category.
Missing-value indicators
Imputation hides the fact that a value was absent. If absence is informative (MNAR, or a form field people skip for a reason), pass add_indicator=True. The imputer then appends a binary column for each feature that had missing values in the training data.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 1000
X = pd.DataFrame({
"age": rng.normal(40, 10, n),
"income": rng.lognormal(10, 0.5, n),
"city": rng.choice(["Oslo", "Bergen", "Tromso"], n),
})
y = (X["income"] > X["income"].median()).astype(int)
# Higher earners are more likely to hide income (MNAR)
hide = rng.random(n) < np.where(y == 1, 0.5, 0.05)
X.loc[hide, "income"] = np.nan
X.loc[rng.random(n) < 0.1, "city"] = np.nan
def build(add_indicator):
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median", add_indicator=add_indicator)),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="missing")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
return Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
for flag in (False, True):
scores = cross_val_score(build(flag), X, y, cv=5, scoring="roc_auc")
print(f"add_indicator={flag}: {scores.mean():.3f} +/- {scores.std():.3f}")In this synthetic data, missingness depends on the target, so the indicator should raise the score. On real data the gain may be small or zero. Run the comparison with cross-validation rather than assuming the indicator helps.
Model-based imputation
KNNImputer fills a gap using the average of the nearest rows. IterativeImputer models each incomplete column as a function of the others. Both can capture relationships that a single median cannot, which suits MAR data. They cost more to fit and need scaled numeric inputs to measure distance sensibly. They also add parameters to tune and can overfit small datasets.
from sklearn.experimental import enable_iterative_imputer # noqa: F401
from sklearn.impute import IterativeImputer, KNNImputer
knn = KNNImputer(n_neighbors=5)
iterative = IterativeImputer(max_iter=10, random_state=0)The enable_iterative_imputer import is required because the class is still marked experimental.
Letting the model handle it
HistGradientBoostingClassifier and HistGradientBoostingRegressor accept NaN directly. At each split they learn which branch the missing rows should follow. This keeps the "missingness" signal without any extra column. Check that your scikit-learn version and chosen estimator support it before relying on it. Linear models, SVMs and most distance-based models do not.
Keep imputation inside the pipeline
Computing a median over the full dataset before splitting lets validation rows influence the training statistic. That is leakage. The fix is the one used above: put the imputer in a Pipeline, so cross_val_score refits it on each training fold. At serving time the stored training median is applied to new rows.
Common errors
- Imputing before splitting. Statistics come from data the model should not have seen. Fit the imputer on training data only.
- Sentinel values left in place. Replace
-999,"N/A"and similar withNaNfirst. - Mean on skewed data. A few large incomes pull the mean upward. Use the median.
- All-missing columns.
SimpleImputerdrops a column with no observed values atfit, so the output has fewer columns than the input. Remove such columns deliberately, and check output shapes. - Indicator column mismatch.
add_indicator=Trueonly creates columns for features that had gaps in the training data. A feature that is complete in training but hasNaNat serving time gets no indicator, and its gaps are still imputed. Test the pipeline with incomplete rows before deployment. - Imputing the target. Never impute
y. Drop rows with a missing label or treat them as unlabelled data.
Exercise
A loan dataset has an employment_years column that is 30 percent empty. Applicants with a very short work history often leave it blank. You plan to use logistic regression. Which imputation setup would you choose, and why?
Show answer
Use SimpleImputer(strategy="median", add_indicator=True) inside a Pipeline, followed by scaling. The blanks likely correlate with the target (MNAR), so the indicator column preserves that signal that the median would hide. The median is robust to outliers such as very long careers. Fitting the imputer inside the pipeline keeps validation folds from influencing the median. Logistic regression cannot handle NaN natively, so imputation is required. Compare against a no-indicator version with cross-validation to confirm the indicator helps.
Exercise
Your pipeline was trained on data where age had missing values. At serving time, a new request has income missing, but income was complete in every training row and the imputer used add_indicator=True. What happens, and how would you guard against it?
Show answer
The imputer found no missing values for income in training, so it learned no fill statistic worth using and created no indicator column for it. At serving time the NaN reaches the model and either raises an error or is handled inconsistently, depending on the step. Guard against it by testing the pipeline with artificially blanked rows, by using SimpleImputer(keepemptyfeatures=True) where appropriate, or by validating and handling unexpected NaN before the request reaches the pipeline.