Sub topic 3
Choosing a Strategy: mean, median, most_frequent, constant
This chapter assumes you can run fit and transform on a scikit-learn estimator, read a NumPy array with np.nan, and tell training data from test data. You have already seen SimpleImputer learn values into statistics_. Now you will decide which statistic it should learn.
What the strategy controls
The strategy parameter sets how the imputer computes one fill value per column during fit. Every strategy ignores missing entries when it computes that value. The default is "mean".
| Strategy | Fill value | Works on | Typical use |
|---|---|---|---|
| `"mean"` | Column average | Numeric only | Roughly symmetric numeric data |
| `"median"` | Middle value | Numeric only | Skewed data or data with outliers |
| `"most_frequent"` | Most common value | Numeric and categorical | Categories, codes, discrete counts |
| `"constant"` | The `fill_value` you give | Numeric and categorical | A deliberate placeholder |
Mean
The mean uses every observed value, so it keeps the column average unchanged after imputation. That is a good property when the data is roughly symmetric.
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]]Column 0 has observed values 1 and 7, so its mean is 4. Column 1 has 2 and 3, so its mean is 2.5.
Median
A single extreme value drags the mean toward it. The median does not move much, so it is the safer choice for skewed columns such as income, prices, or durations.
import numpy as np
from sklearn.impute import SimpleImputer
X_train = np.array([[1.0], [2.0], [np.nan], [100.0]])
X_test = np.array([[np.nan], [5.0]])
imputer = SimpleImputer(strategy="median")
imputer.fit(X_train) # learns the median of the training data only
print(imputer.statistics_) # [2.]
print(imputer.transform(X_test))
# [[2.]
# [5.]]The observed training values are 1, 2 and 100. The mean would be about 34.3, which describes none of the rows. The median is 2.
most_frequent
This strategy fills with the mode, the value that appears most often. It is the usual choice for categorical columns, because a mean of strings does not exist. It also suits numeric columns that hold codes or small counts.
If two values appear equally often, the imputer picks the smallest one. For strings, "smallest" means first in sorted order.
constant
The constant strategy ignores the data and fills with fill_value. Use it when the fill should be a stated placeholder instead of an estimate. Here -1 marks missing entries in the input, and 0 replaces them.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1, -1],
[-1, 4],
[3, 6]])
imputer = SimpleImputer(missing_values=-1, strategy="constant", fill_value=0)
print(imputer.fit_transform(X))
# [[1 0]
# [0 4]
# [3 6]]If you omit fill_value, numeric columns are filled with 0. String columns are filled with "missing_value".
Common errors
- Mean or median on strings.
SimpleImputer(strategy="mean")raises aValueErrorwhen the data contains strings. Usemost_frequentorconstantfor those columns. - One strategy for the whole frame. A single imputer applies one strategy to every column it receives. Mixed data needs separate imputers, which a later chapter builds with
ColumnTransformer. - Mean on skewed data. The code runs without error, but the filled values are unrepresentative. Check the column's histogram or compare its mean and median first.
- Treating the fill as real data. Any single fill value shrinks the column's variance, because many rows now share one number. Heavy imputation can make a feature look more certain than it is.
A quick selection rule
- Is the column text or a category? Use
most_frequent, orconstantif you want an explicit "missing" label. - Is it numeric with outliers or heavy skew? Use
median. - Is it numeric and roughly symmetric? Use
mean. - Do you have a domain reason for a specific value, such as 0 for "no purchases"? Use
constant.
Exercise
A column holds house prices: 200, 210, 220, 230 and 5000, plus one missing entry. You must fill the missing entry with a column statistic. Which strategy do you pick, which value does it produce, and why not the other numeric option?
Show answer
Pick median. The five observed values sorted are 200, 210, 220, 230, 5000, so the median is 220. The mean would be 1172, pulled far upward by the outlier 5000, and it would be higher than four of the five observed prices.
Exercise
You run SimpleImputer(strategy="mean") on a column containing "Oslo", "Rome" and NaN. What happens, and what are two valid fixes?
Show answer
It raises a ValueError, because a mean cannot be computed for strings. Two fixes are strategy="most_frequent", which fills with the most common city, and strategy="constant" with fill_value="missing", which creates an explicit missing category.