Sub topic 4
Handling missing values
This chapter assumes you know pandas, the scikit-learn fit/transform workflow, and why a model is evaluated on data it did not train on. It covers how to find missing values, fill them in, and flag them, all without leaking information from the test set.
Why missingness needs a decision
Most scikit-learn estimators raise an error when a column contains NaN. Some, such as HistGradientBoostingClassifier, accept missing values natively. For everything else you must either drop rows or fill the gaps, which is called imputation.
Dropping rows is the simplest option. It throws away data, and it biases the sample if the missing rows differ from the complete ones. Imputation keeps the rows but needs a rule.
Why values go missing
The reason a value is missing affects which fix is safe.
| Pattern | Meaning | Example |
|---|---|---|
| Missing completely at random | Missingness is unrelated to any data | A sensor drops a reading at random |
| Missing at random | Missingness depends on other columns you have | Younger users skip the income field |
| Missing not at random | Missingness depends on the missing value itself | High earners refuse to report income |
In the last case the fact that a value is missing is itself a signal. Filling it silently hides that signal.
Simple imputation with SimpleImputer
SimpleImputer learns one fill value per column during fit and applies it during transform. Common strategies are mean, median, most_frequent and constant.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
X = pd.DataFrame({"age": [25, np.nan, 40, 31], "income": [50000, 62000, np.nan, 58000]})
imputer = SimpleImputer(strategy="median", add_indicator=True)
X_filled = imputer.fit_transform(X)
print(imputer.get_feature_names_out())
print(X_filled)The median is usually safer than the mean for skewed columns such as income, because a few extreme values do not pull it. Use most_frequent or constant for categorical columns.
Missing-value indicators
Setting add_indicator=True appends a binary column for each feature that had missing values in the training data. The column is 1 where the value was missing and 0 otherwise. The model can then learn that "missing" behaves differently from "typical".
Add an indicator when you suspect the data is not missing at random, or when the missing rate is meaningful. Skip it when a column is almost never missing, since it adds a column with little information.
Fit on training data only
The imputer's fill value is a statistic computed from data. If you compute the median on the full dataset before splitting, information from the test rows leaks into training. Fit the imputer on the training split only, then reuse the learned values on validation and test data.
from sklearn.model_selection import train_test_split
X_train, X_test = train_test_split(X, test_size=0.5, random_state=0)
imputer = SimpleImputer(strategy="median")
imputer.fit(X_train)
X_test_filled = imputer.transform(X_test)The safest way to enforce this is to place the imputer inside a Pipeline, a pattern covered in a later chapter.
Other approaches
KNNImputerfills a gap using the average of the nearest rows. It can capture relationships between columns but is slower and needs scaled features.IterativeImputermodels each column from the others. It is more flexible and more expensive. It is still marked experimental and requiresfrom sklearn.experimental import enable_iterative_imputer.- Tree-based models with native support skip imputation entirely and treat missing as its own branch.
Common errors
- Imputing before the train/test split.
- Using the mean on heavily skewed data.
- Filling a categorical column with a number that looks like a real category.
- Forgetting that a column with no missing values in training can still have them in production. Set a strategy so that
transformdoes not fail on newNaNs.
Exercise
A column "income" is missing for many high earners who decline to answer. Which imputation strategy and extra option would you use, and why?
Show answer
Use the median strategy, because income is skewed, together with add_indicator=True. The missingness depends on the value itself, so the indicator column lets the model learn from the fact that income was missing. Fit the imputer on the training split only.