Sub topic 1
Filling Missing Values with scikit-learn’s SimpleImputer
Prerequisites
Assume you know basic Python, NumPy arrays, pandas DataFrames, and the scikit-learn fit and transform pattern. You should also know that training data and test data must be kept separate.
Why missing values need handling
A feature matrix contains the input columns used by a model. A missing value is often represented by NaN, which means “not a number” or “no recorded value.” It may result from a skipped survey question, a failed measurement, or a missing database field.
Many scikit-learn estimators cannot calculate with NaN. For example, a linear model cannot compute a coefficient if one of its arithmetic inputs is missing. Imputation replaces each missing entry with a chosen value.
Imputation does not recover the original value. It creates a reasonable substitute so that the model can process the row.
Your first SimpleImputer: fit, transform and statistics_
SimpleImputer learns replacement values during fit. It applies those values during transform. The learned values are stored in statistics_.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([
[1.0, 2.0],
[np.nan, 3.0],
[7.0, np.nan],
])
imputer = SimpleImputer(strategy="mean")
X_filled = imputer.fit_transform(X)
print(imputer.statistics_) # [4. 2.5]
print(X_filled)
# [[1. 2. ]
# [4. 3. ]
# [7. 2.5]]The first column has a mean of 4. The second column has a mean of 2.5. Existing values remain unchanged.
Choosing a strategy
Choose a strategy that matches the column’s type and distribution.
| Strategy | Typical use |
|---|---|
| `mean` | Numeric data without strong outliers |
| `median` | Numeric data with skew or outliers |
| `most_frequent` | Categorical or discrete values |
| `constant` | A deliberate fixed value such as `0` or `"Unknown"` |
The mean is sensitive to extreme values. The median is the middle value after sorting and is more resistant to outliers. For categories, use most_frequent or constant rather than a numeric average.
Exercise
Which strategy would you choose for an income column containing a few very large salaries, and why?
Show answer
Choose median, because a few large outliers can pull the mean upward.