Sub topic 3
Choosing a strategy: mean, median, most_frequent, constant
This chapter assumes you can fit and transform with a scikit-learn estimator and that you have run SimpleImputer once on a small array. It also assumes you can read a NumPy array with np.nan in it and that you know what a skewed distribution is. The earlier chapters introduced fit, transform and statistics_. Here the question is which value the imputer should learn.
Why the strategy matters
SimpleImputer fills every missing entry in a column with one value. The strategy parameter decides how that value is chosen. The default is "mean". A wrong choice does not raise an error. The pipeline runs, and the model quietly trains on distorted data.
The four built-in strategies are:
| Strategy | Fill value | Works on | Typical use |
|---|---|---|---|
| `"mean"` | Average of the observed values in the column | Numeric only | Roughly symmetric numeric columns |
| `"median"` | Middle of the observed values in the column | Numeric only | Skewed columns or columns with outliers |
| `"most_frequent"` | The mode, the most common observed value | Numeric and string | Categorical columns, binary flags, ratings |
| `"constant"` | The `fill_value` you supply | Numeric and string | Missing has a known meaning, or you want a marker category |
Each column is handled independently. The imputer computes one statistic per column during fit and stores the statistics in statistics_. Observed values are the non-missing ones. Missing entries never contribute to the statistic.
Mean
The mean is the sum of the observed values divided by their count. It is a reasonable default when the column is roughly symmetric and has no extreme values. Filling with the mean leaves the column's mean unchanged.
The mean has two weaknesses.
- Outliers pull it. One extreme value shifts the fill value for every missing row.
- It shrinks the spread. Every imputed row gets the same value. If 30% of a column is missing, 30% of the rows now sit exactly at the center, so the variance falls. Models that rely on a column's spread, or on its correlation with other columns, see weaker signals than the real data would show.
The second weakness applies to every strategy in this chapter, because all of them insert a single value. It is the main reason to know the alternatives at the end of the tutorial.
Do not mean-impute columns that only look numeric. A label-encoded category such as city = 0, 1, 2 has no meaningful average, and a fill value of 1.4 is not a city. Treat those columns as categorical.
Median
The median is the middle of the sorted observed values. With an even count, scikit-learn averages the two middle values. A few extreme values barely move it.
The next example compares the strategies on a column with one large outlier.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([[1.0], [2.0], [3.0], [np.nan], [100.0]])
for strategy in ["mean", "median", "most_frequent"]:
imputer = SimpleImputer(strategy=strategy)
imputer.fit(X)
print(strategy, imputer.statistics_)
# mean [26.5]
# median [2.5]
# most_frequent [1.]The observed values are 1, 2, 3 and 100. The mean is 106 / 4 = 26.5, which is larger than three of the four values. The median is (2 + 3) / 2 = 2.5, which describes the typical row much better. Filling the missing entry with 26.5 would make that row look like an outlier too.
Prefer the median when the column is right-skewed. Income, prices, durations, and counts of events are common examples. If you are unsure, compare mean and median on the training column. A large gap between them signals skew or outliers, and the median is the safer choice.
The median costs little. It also keeps its meaning on discrete numeric columns. On a symmetric column the median and mean nearly coincide, so little is lost by choosing the median by default.
most_frequent
"most_frequent" fills with the mode, the value that occurs most often among the observed entries. It is the only built-in statistic other than constant that accepts strings, so it is the standard choice for categorical columns.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["red"], ["blue"], ["blue"], [np.nan], ["red"]], dtype=object)
imputer = SimpleImputer(strategy="most_frequent")
print(imputer.fit_transform(X))
print(imputer.statistics_)
# [['red']
# ['blue']
# ['blue']
# ['blue']
# ['red']]
# ['blue']Here "red" and "blue" each appear twice. When several values tie, SimpleImputer returns the smallest one. For strings that means alphabetical order, so "blue" wins. This rule is deterministic but arbitrary. A tie is a sign that the mode is a weak summary of the column.
most_frequent also suits numeric columns that behave like categories:
- Binary flags such as
has_garagecoded 0 and 1. - Ordinal ratings from 1 to 5.
- Small integer codes whose average would not mean anything.
On a continuous column, most_frequent is a poor choice. When almost every value is unique, the mode is just the smallest value, as the 1. in the earlier output shows.
most_frequent can also amplify imbalance. If 90% of observed rows are "Oslo", every missing row becomes "Oslo", and the column looks even more lopsided than the real data.
constant
"constant" does not look at the data. It fills every missing entry with the fill_value you provide. The fill value is not learned, so the column's distribution has no effect on it.
Use it when the missing entry has a known meaning:
- Absence means zero. A column
num_late_paymentsthat is empty for customers with no late payments should be filled with 0. The mean would invent late payments that never happened. - Missing is its own category. For a categorical column, a fill such as
"unknown"lets the model treat missingness as a level of its own, instead of merging those rows into the most common category. - Tree models and out-of-range markers. A value such as
-1in a column that is otherwise positive lets a decision tree split missing rows from observed rows.
If you leave fill_value as None, scikit-learn picks a default. It uses 0 for numeric data and the string "missing_value" for strings and object columns.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["Oslo"], [np.nan], ["Rome"]], dtype=object)
imputer = SimpleImputer(strategy="constant")
print(imputer.fit_transform(X))
# [['Oslo']
# ['missing_value']
# ['Rome']]The default of 0 is dangerous for numeric columns where 0 is a real value. Filling an age or temperature column with 0 makes missing rows look like newborns or freezing days. State fill_value explicitly, even when the default would work, so that a reader knows the choice was deliberate. A later chapter covers fill_value for categorical columns in more detail.
Deciding between strategies
The choice depends on two things: the column type and what a missing entry means. The diagram turns that into a sequence of questions.
Keep these rules of thumb in mind when you read the flow:
- Binary flags and ratings count as the "No" branch of the first question, even though they are stored as numbers.
- When both
meanandmedianseem acceptable, pickmedian. It is the more robust of the two. - Choose by what you know about how the data was collected, not only by its shape. A mean cannot recover a zero that was never recorded.
Errors you will meet
Mean or median on text
"mean" and "median" need numbers. If a column holds strings, fit raises a ValueError.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["Oslo"], [np.nan], ["Rome"]], dtype=object)
try:
SimpleImputer(strategy="mean").fit(X)
except ValueError as error:
print("ValueError:", "mean needs numeric data")
# ValueError: mean needs numeric dataThe fix is to use most_frequent or constant for that column. In a mixed DataFrame, send numeric and text columns to different imputers with a ColumnTransformer. That is the topic of a later chapter.
A typo in the strategy name
strategy accepts only the four names above. Anything else, such as "mode" or "average", fails when you call fit with a ValueError that lists the allowed values. Scikit-learn validates parameters at fit time, not when you construct the object, so the error can appear far from the line that contains the typo.
Constant fill with the wrong type
With strategy="constant", a numeric column needs a numeric fill_value. A string fill value on a numeric column raises an error, because the value cannot be stored in the column's dtype. Pass a number for numeric columns and a string for text columns.
Reading the wrong fitted attribute
For mean, median and most_frequent, statistics_ holds what was learned from the data. For constant it simply echoes the fill value. In both cases statistics_ is the quickest way to check, after fitting, what the imputer will insert. Do this check on every new dataset, because a surprising value such as a huge mean points to an outlier or a data entry error.
Putting the choice in practice
A typical mixed table needs more than one strategy at once. Here is the same reasoning applied column by column.
| Column | Observed pattern | Missing means | Strategy |
|---|---|---|---|
| `age` | Roughly symmetric | Not recorded | `mean` or `median` |
| `income` | Right-skewed, a few very high values | Not recorded | `median` |
| `num_children` | Small integers | Not recorded | `most_frequent` |
| `num_late_payments` | Small integers | None occurred | `constant`, `fill_value=0` |
| `city` | Text categories | Not recorded | `most_frequent` or `constant`, `fill_value="unknown"` |
One SimpleImputer object has one strategy. To use different strategies for different columns, create one imputer per group of columns. You will wire that up in a later chapter. For now, the point is that the strategy is a per-column decision, and the right default for a whole table does not exist.
Summary of trade-offs
meankeeps the column average but is sensitive to outliers.medianresists outliers and is the safer numeric default.most_frequenthandles text and category-like numbers but can overstate the common category and breaks ties by picking the smallest value.constantencodes domain knowledge or a marker, and the default fill of 0 can be wrong.- Every strategy shrinks the column's variance, because all imputed rows share one value.
Exercise
A numeric column contains the values 4, NaN, 4, 10, 1, 1. What fill value does SimpleImputer learn with strategy="mean", "median" and "most_frequent"? Give the three numbers.
Show answer
The observed values are 4, 4, 10, 1, 1. The mean is 20 / 5 = 4.0. Sorted they are 1, 1, 4, 4, 10, so the median is 4.0. The values 4 and 1 each appear twice, and a tie returns the smallest value, so most_frequent gives 1.0.
Exercise
A column annualbonus is empty for employees who did not receive a bonus. Which strategy should you use and with what fillvalue? Explain why mean imputation would be wrong here.
Show answer
Use strategy="constant" with fill_value=0. A missing entry means the bonus was zero, so 0 is the true value. Mean imputation would give those employees the average bonus of people who did receive one, which invents money that was never paid and distorts the column.
Exercise
You call SimpleImputer(strategy="median").fit(X) on an object column containing "Oslo", "Rome" and np.nan. What happens, and which two strategies could you use instead?
Show answer
fit raises a ValueError, because the median needs numeric data. You could use strategy="mostfrequent" to fill with the most common city, or strategy="constant" with a fillvalue such as "unknown" to give missing rows their own category.