Sub topic 11
Missing values in categorical columns
This chapter assumes you can use pandas DataFrames, know what fit and transform do in scikit-learn, and have seen get_dummies and OneHotEncoder from earlier chapters.
Why missing values need a decision
Real categorical columns often contain gaps. A customer skipped the "color" field, or a join found no match. In pandas these gaps appear as NaN or None. A model cannot use NaN as a category, so you must decide what the encoder does with it. The tools differ in their defaults, so check what yours does.
What get_dummies does
By default, get_dummies creates no column for missing values. A row with NaN gets zeros in every indicator column.
import numpy as np
import pandas as pd
df = pd.DataFrame({"color": ["red", np.nan, "blue", "red"]})
print(pd.get_dummies(df, columns=["color"], dtype=int))
print(pd.get_dummies(df, columns=["color"], dummy_na=True, dtype=int))The first call gives color_blue and color_red, and the second row is all zeros. The second call adds dummy_na=True, which creates a color_nan column that is 1 for the missing row.
An all-zero row is ambiguous. It is the same pattern you would get from a category you chose to drop, so the model cannot tell "missing" from "baseline".
What OneHotEncoder does
Since scikit-learn 0.24, OneHotEncoder treats NaN as a category of its own. It learns the missing value during fit and gives it a column, sorted last.
import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"color": ["red", np.nan, "blue", "red"]})
enc = OneHotEncoder(sparse_output=False)
print(enc.fit_transform(df))
print(enc.get_feature_names_out())The feature names are color_blue, color_red and color_nan. The NaN row is [0, 0, 1], so it is distinguishable from every real category.
Missingness is learned like any other category. If the training data has no NaN but the test data does, the encoder sees an unknown category. With handle_unknown="error" (the default) it raises an error. With handle_unknown="ignore" the row becomes all zeros, as described in the chapter on unseen categories.
Imputing before encoding
Sometimes you want an explicit label instead. Putting a SimpleImputer before the encoder fills the gaps with a constant, and the fill value then appears in the feature names.
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({"color": ["red", np.nan, "blue", "red"]})
cat = Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="missing")),
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
])
print(cat.fit_transform(df))
print(cat.get_feature_names_out())The columns are color_blue, color_missing and color_red. A major benefit is that the "missing" column is always created, because the imputer fills it before the encoder sees the data.
Another option is strategy="most_frequent", which replaces gaps with the most common category. This is simple but hides the fact that a value was missing, and it can add bias.
Choosing an approach
| Approach | Missing row becomes | Use when |
|---|---|---|
| `get_dummies` default | All zeros | Quick exploration, and you accept the ambiguity |
| `get_dummies(dummy_na=True)` | A `_nan` column of 1 | Exploration where missingness matters |
| `OneHotEncoder` default | Its own `nan` column | Missingness is informative and present in training |
| `SimpleImputer` constant, then encoder | A named "missing" column | You want a stable, explicit column in a pipeline |
| `SimpleImputer` most frequent | The most common category | Missingness is random and rare |
Exercise
Your training data has no missing values in a "plan" column, but production data sometimes does. You use OneHotEncoder(handle_unknown="ignore") with no imputer. What happens to a production row where "plan" is NaN, and how could you make that case explicit?
Show answer
The encoder never learned NaN as a category, so it treats it as unknown and outputs all zeros for that column. To make it explicit, add SimpleImputer(strategy="constant", fill_value="missing") before the encoder. The "missing" column then exists from training onward, and the model can learn a weight for it if training data includes missing rows.