Sub topic 5
Imputing categorical columns and setting fill_value
This chapter assumes you know the SimpleImputer fit/transform pattern and the strategy parameter from the earlier chapters. You should also be comfortable with pandas DataFrames and the difference between numeric and string columns.
Why categorical columns need different strategies
The mean and median strategies do arithmetic, so they only work on numbers. If you apply them to a column of strings, SimpleImputer raises a ValueError at fit time. Two strategies work on both numbers and strings:
| Strategy | Numeric columns | Categorical (string) columns | Fill value |
|---|---|---|---|
| `mean` | Yes | No, raises `ValueError` | Learned from data |
| `median` | Yes | No, raises `ValueError` | Learned from data |
| `most_frequent` | Yes | Yes | Learned from data |
| `constant` | Yes | Yes | You choose with `fill_value` |
The rest of the chapter covers those two options in turn.
most_frequent: fill with the mode
The most_frequent strategy learns the most common value in each column during fit and stores it in statistics_.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["Oslo"], ["Rome"], [np.nan], ["Oslo"]], dtype=object)
imputer = SimpleImputer(strategy="most_frequent")
X_filled = imputer.fit_transform(X)
print(imputer.statistics_) # ['Oslo']
print(X_filled)
# [['Oslo']
# ['Rome']
# ['Oslo']
# ['Oslo']]Two details matter here.
- The array uses
dtype=object, which is how NumPy stores mixed or string data that containsnp.nan. A DataFrame column of strings with missing entries is already an object column. - When two values tie for most frequent, scikit-learn picks the smallest one. For strings, that means the first in sorted order. A column with
["b", "a", nan]is filled with"a".
The weakness of this strategy is that it invents data. Every missing row now claims to be the most common category, which can overstate that category's share.
constant and fill_value: fill with a label you choose
The constant strategy replaces every missing entry with the fill_value you give it. This is often the better choice for categorical data, because it turns "missing" into a category of its own.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["Oslo"], ["Rome"], [np.nan], ["Oslo"]], dtype=object)
imputer = SimpleImputer(strategy="constant", fill_value="unknown")
print(imputer.fit_transform(X))
# [['Oslo']
# ['Rome']
# ['unknown']
# ['Oslo']]If you leave fill_value unset, scikit-learn chooses a default based on the data. Numeric columns get 0, and string columns get the text "missing_value". Setting the value yourself is clearer, because the label then appears in your encoded feature names.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["Oslo"], [np.nan]], dtype=object)
print(SimpleImputer(strategy="constant").fit_transform(X))
# [['Oslo']
# ['missing_value']]Choose a label that cannot collide with a real category. If your data already contains a city called "unknown", filling with "unknown" silently merges the two groups.
Marker values other than NaN
Imputation only fills entries that match missing_values, which defaults to np.nan. Real data often stores gaps as None, an empty string, or a text marker such as "?". Convert those to np.nan first, or tell the imputer what to look for.
import numpy as np
from sklearn.impute import SimpleImputer
X = np.array([["Oslo"], ["?"], ["Rome"], ["?"], ["Oslo"]], dtype=object)
imputer = SimpleImputer(missing_values="?", strategy="most_frequent")
print(imputer.fit_transform(X).ravel())
# ['Oslo' 'Oslo' 'Rome' 'Oslo' 'Oslo']Here the "?" entries are treated as missing and never counted when finding the most frequent value.
Imputing before encoding
Most estimators cannot read strings, so a categorical column is usually one-hot encoded afterward. Impute first, then encode. If you encode first, a NaN may cause an error or be treated inconsistently, depending on the encoder.
With constant, the filled label becomes a real category, and the encoder creates a column for it. With most_frequent, no new column appears, because the filled rows share the existing category's column.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"city": ["Oslo", "Rome", np.nan, "Oslo"]})
cat = Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="unknown")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
])
cat.fit(df)
print(cat.named_steps["onehot"].categories_)
# [array(['Oslo', 'Rome', 'unknown'], dtype=object)]The encoder sees three categories, so a model can learn a separate weight for "unknown".
Choosing between the two
- Use
constantwhen the absence of a value may carry meaning. A blank "referral source" field often means something different from any listed source. - Use
most_frequentwhen gaps look random and you want to avoid adding a category. It is also the usual choice for numeric columns that hold codes rather than quantities. - Whichever you choose, fit the imputer on training data only, as covered in the leakage chapter.
Exercise
A column color contains "red", "blue", "red", "green", and two missing entries stored as the text "n/a". Write the SimpleImputer call that fills the gaps with the category "unspecified". What does the column look like afterward?
Show answer
Use SimpleImputer(missing_values="n/a", strategy="constant", fill_value="unspecified"). Because "n/a" is text and not NaN, you must pass it through missing_values. After fit_transform, the two "n/a" entries become "unspecified", giving red, blue, red, green, unspecified, unspecified (in the original row order), and "unspecified" becomes its own category.