Sub topic 5
Imputing categorical columns and setting fill_value
This chapter covers how SimpleImputer handles text and category columns, and how fill_value controls the constant it writes. It assumes you know the fit/transform pattern, have used SimpleImputer on numeric data, and know what ColumnTransformer and Pipeline are. The examples need scikit-learn 1.2 or later.
Why categorical columns need different strategies
Categorical columns hold labels such as "Oslo" or "free". A label has no mean or median, so two of the four strategies do not apply. The other two do:
| Strategy | Works on text? | What it writes into the gaps |
|---|---|---|
| `mean` | No | The column mean. Raises `ValueError` on non-numeric data. |
| `median` | No | The column median. Raises `ValueError` on non-numeric data. |
| `most_frequent` | Yes | The mode of each column, learned during `fit`. |
| `constant` | Yes | The single value in `fill_value`. |
Both strategies that work on text also work on numeric columns. most_frequent is a reasonable choice for a numeric 0/1 flag. The same is true for integer codes that stand for categories.
The two strategies make different assumptions. most_frequent assumes a missing entry probably looks like a typical row. constant makes no such assumption. It labels missing entries with a value that stands for "unknown".
most_frequent on text columns
The imputer learns one mode per column. The next example uses a DataFrame with two text columns that each contain gaps.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({
"city": ["Oslo", "Rome", np.nan, "Oslo", np.nan],
"size": ["S", "M", "L", np.nan, "M"],
})
imputer = SimpleImputer(strategy="most_frequent")
filled = imputer.fit_transform(df)
print(imputer.statistics_) # ['Oslo' 'M']
print(pd.DataFrame(filled, columns=imputer.get_feature_names_out()))The output is:
city size
0 Oslo S
1 Rome M
2 Oslo L
3 Oslo M
4 Oslo Mstatistics_ holds the learned mode for each column. In city, "Oslo" appears twice and "Rome" once, so "Oslo" fills both gaps. In size, "M" appears twice, so it fills the one gap.
Two details are worth knowing.
- The result is an object array. A fitted
SimpleImputerreturns the same kind of dtype it received, so text in gives text out. Wrap it in a DataFrame if you want column names back. - Ties are broken toward the smallest value. With the labels
"b"and"a"appearing once each, the imputer picks"a". The tie-break is deterministic but arbitrary. If two categories are nearly tied, the filled value says very little about the missing row.
constant and the fill_value parameter
fill_value only matters when strategy="constant". With any other strategy it is ignored. It takes a single scalar, which the imputer writes into every gap in every column it handles.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
df = pd.DataFrame({
"city": ["Oslo", "Rome", np.nan, "Oslo", np.nan],
"size": ["S", "M", "L", np.nan, "M"],
})
imputer = SimpleImputer(strategy="constant", fill_value="unknown")
filled = imputer.fit_transform(df)
print(imputer.statistics_) # ['unknown' 'unknown']
print(pd.DataFrame(filled, columns=imputer.get_feature_names_out()))The output is:
city size
0 Oslo S
1 Rome M
2 unknown L
3 Oslo unknown
4 unknown MFor constant, statistics_ simply repeats fill_value once per column. Nothing is learned from the data. It is still good practice to call fit, so the imputer records the number of columns and, if you pass a DataFrame, their names.
The default fill_value
If you choose constant and leave fill_value as None, scikit-learn picks a default from the data type:
- Numeric data gets
0. - String or object data gets the string
"missing_value".
The default works, but an explicit label is easier to read in reports and in one-hot feature names. Compare city_missing_value with city_unknown. Pick one label and use it consistently across columns.
Type compatibility
The type of fill_value has to match the data. A numeric array cannot receive a string, and the imputer refuses rather than quietly converting the array to text.
import numpy as np
from sklearn.impute import SimpleImputer
X_num = np.array([[1.0], [np.nan], [3.0]])
try:
SimpleImputer(strategy="constant", fill_value="unknown").fit(X_num)
except ValueError:
print("ValueError: a string fill_value cannot go into numeric data")
X_text = np.array([["a"], [np.nan], ["b"]], dtype=object)
try:
SimpleImputer(strategy="mean").fit(X_text)
except ValueError:
print("ValueError: mean needs numeric data")Both calls raise ValueError, so the script prints both messages. If you see a similar error in a real pipeline, a column is usually the wrong dtype. A common cause is a numeric column that was read as text because one cell contained "N/A". Fix the column, or declare "N/A" as the missing marker (see the callout below).
Choosing between most_frequent and constant
The decision depends on what a missing entry means in your data.
Use these rules of thumb:
- Choose
constantwhen "no answer" is a meaningful state. A survey field left blank is a real group of people, and a separate"unknown"category lets the model treat them as a group. - Choose
most_frequentwhen gaps come from random data loss and one category clearly dominates. It leaves the column's value counts almost unchanged. - Prefer
constantwhen the top categories are nearly tied, because the mode is then an arbitrary pick. - Prefer
constantfor rare categories with few examples. Filling with the mode inflates the majority class and can hide a real minority signal.
Imputing with the mode makes the column look more certain than it is. The gaps now look like ordinary observations, and the model has no way to tell them apart. Indicator columns, covered in a later chapter, restore that signal.
Different settings for different columns
One SimpleImputer applies a single strategy and a single fill_value to every column it sees. For per-column choices, use a ColumnTransformer with one imputer per column or group of columns.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
df = pd.DataFrame({
"city": ["Oslo", "Rome", np.nan, "Oslo"],
"plan": ["free", np.nan, "pro", "free"],
})
ct = ColumnTransformer(
[
("city", SimpleImputer(strategy="constant", fill_value="unknown"), ["city"]),
("plan", SimpleImputer(strategy="most_frequent"), ["plan"]),
],
verbose_feature_names_out=False,
)
out = ct.fit_transform(df)
print(pd.DataFrame(out, columns=ct.get_feature_names_out()))The output is:
city plan
0 Oslo free
1 Rome free
2 unknown pro
3 Oslo freeThe missing city became "unknown", and the missing plan became "free", the most common plan. verbose_feature_names_out=False keeps the original column names instead of prefixing them with the transformer name.
Imputation before encoding
Most estimators cannot read strings, so a categorical column is usually one-hot encoded after imputation. Order matters here. Imputation comes first, so the encoder sees a complete column and the "unknown" label becomes a normal category with its own output column.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({
"city": ["Oslo", "Rome", np.nan, "Oslo"],
"plan": ["free", np.nan, "pro", "free"],
})
prep = ColumnTransformer([
("cat", Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="unknown")),
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
]), ["city", "plan"]),
])
Xt = prep.fit_transform(df)
print(prep.get_feature_names_out())
print(Xt)get_feature_names_out() returns six names, in this order: cat__city_Oslo, cat__city_Rome, cat__city_unknown, cat__plan_free, cat__plan_pro, cat__plan_unknown. The encoded matrix is:
[[1. 0. 0. 1. 0. 0.]
[0. 1. 0. 0. 0. 1.]
[0. 0. 1. 0. 1. 0.]
[1. 0. 0. 1. 0. 0.]]Row 2 has a 1 in city_unknown, and row 1 has a 1 in plan_unknown. The model gets a column that says "this value was missing", without you building an indicator by hand.
The two steps fit on training data only, which the next chapter covers. When this pipeline later sees a city it never saw in training, handle_unknown="ignore" encodes it as all zeros in that column group. The imputer does not matter here, because an unseen label is not a missing one.
A shortcut: let the encoder handle NaN
OneHotEncoder treats NaN as a category of its own. For a pure one-hot pipeline you can skip the imputer and get a city_nan column. Keep the imputer when:
- the model does not use one-hot encoding, such as an ordinal encoding that rejects NaN in your scikit-learn version;
- you want
most_frequentfilling instead of a separate category; - you want a readable label like
"unknown"in the feature names.
Integer-coded categories
Categorical data is sometimes already stored as integers, for example 1 for red, 2 for green and 3 for blue, with np.nan for gaps. That makes the array a float array, because NaN is a float.
meanandmedianrun without error, but they produce meaningless codes such as1.67. The numbers are labels, not quantities, so these strategies hide a modelling mistake.most_frequentreturns a real code, such as2.0.constantwith a code outside the real range, such as-1or0, creates an "unknown" category. Pick a value that none of the real codes use, or the unknown group merges with a real one.
The same warning applies to text. Never choose a fill_value that already appears in the column. If "unknown" is already a legitimate answer in your data, the imputer silently merges the gaps with it.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Using `mean` on text columns | `ValueError` during `fit` | Switch to `most_frequent` or `constant`. |
| Passing `fill_value="unknown"` for a numeric column | `ValueError` during `fit` | Use a number, or move the column to a text imputer. |
| Setting `fill_value` but leaving `strategy="mean"` | `fill_value` is ignored without any warning | Set `strategy="constant"`. |
| One imputer for numeric and text columns together | The data becomes object dtype, or `fit` raises an error | Split the columns with `ColumnTransformer`. |
| Placeholders like `"?"` left in the column | They are treated as real categories | Pass `missing_values="?"`. |
| A `fill_value` that already exists as a category | Gaps merge with that category | Use a label that never appears. |
Where this leads
You can now fill categorical gaps with a mode or a label, and apply a different rule to each column. Everything above fits the imputer on the data you hand it. The next chapter looks at what that means when you split the data into training and test sets. Without care, statistics such as the mode leak information from the test set into the training step.
Exercise
A DataFrame column color contains ["red", "blue", np.nan, "blue", "red", np.nan, "green"]. You fit SimpleImputer(strategy="most_frequent") on it. What does statistics_ contain, and why?
Show answer
It contains ['blue'] as the imputed value. "red" and "blue" each appear twice, and the imputer breaks ties by taking the smallest value in sorted order. Alphabetically "blue" comes before "red". Because the tie is broken arbitrarily, constant with a label such as "unknown" might be the safer choice for this column.
Exercise
You build SimpleImputer(strategy="most_frequent", fill_value="unknown") on a text column and expect the gaps to become "unknown". What actually happens?
Show answer
The gaps are filled with the most frequent category. fill_value is only used when strategy="constant", so scikit-learn ignores it here. To get "unknown", change the strategy to "constant".
Exercise
A pipeline imputes a column of names with SimpleImputer(strategy="constant", fill_value=0) and the column contains strings. Why is this a poor design, and what is a better one?
Show answer
A numeric fill_value in a text column would mix numbers into text data, and in a one-hot step the 0 would become a category with a confusing name. The type of fill_value should match the column. Use a descriptive string such as "unknown" for text columns, or use a number for numeric columns and keep the two types in separate ColumnTransformer branches.