Sub topic 11
Missing values in categorical columns
Real datasets rarely have a value in every cell. A survey respondent skips a question, a sensor drops a reading, or a join finds no match. This chapter covers what one-hot encoding does with such gaps and how to choose a strategy on purpose.
This chapter assumes you can use pandas DataFrames and know how OneHotEncoder and get_dummies work. It also assumes you know why encoders are fitted on training data only, and that you have seen a ColumnTransformer. Examples use scikit-learn 1.2 or later, where the dense-output argument is sparse_output.
What counts as missing
In a categorical column, a missing value is usually np.nan, None, or pd.NA. Pandas treats all three as missing, so isna() finds them. Models cannot use them directly, because a missing value is not a category label and has no numeric meaning.
You have three basic choices:
- Treat "missing" as its own category.
- Fill the gap with a plausible real category, such as the most common one.
- Leave the row without any indicator, so all indicator columns are 0.
Each choice gives the model different information, so the right one depends on why the value is missing.
How get_dummies handles missing values
By default, pd.get_dummies skips missing values. The row gets 0 in every indicator column, as if it belonged to no category. With dummy_na=True, it adds one more column that marks the missing rows.
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 returns only color_blue and color_red, and the second row is all zeros. The second call adds color_nan, which is 1 only in that row.
The default behavior has a cost. An all-zero row looks the same as a category that was never encoded. With drop_first=True, the first category is also represented by all zeros, so a missing row and a first-category row become indistinguishable. If you use get_dummies and care about missingness, set dummy_na=True.
get_dummies is also stateless. Calling it on a test set with a different set of missing values can produce different columns than the training set. The next section covers how OneHotEncoder avoids that.
How OneHotEncoder handles missing values
OneHotEncoder treats missing values as a category of their own. When it finds np.nan during fit, it learns it like any other value and creates a column for it.
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 encoder sorts categories and puts missing values last. The output columns are color_blue, color_red, and color_nan. The second row is [0, 0, 1].
This means a missing value does not raise an error during fit. That is convenient, but it also means missingness can enter the model without you deciding it should. If you want a different treatment, handle the gaps before the encoder.
Missing values that appear only at prediction time
The encoder learns "missing" as a category only if it sees a missing value in the training data. If the training data has no gaps, then a missing value in new data is an unknown category.
import numpy as np
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
train = pd.DataFrame({"color": ["red", "green", "blue"]})
test = pd.DataFrame({"color": ["green", np.nan]})
enc = OneHotEncoder(handle_unknown="ignore", sparse_output=False)
enc.fit(train)
print(enc.transform(test))The output is [[0, 1, 0], [0, 0, 0]]. The columns are blue, green, and red, so the second row is all zeros. With the default handle_unknown="error", the same call raises a ValueError that names nan as an unknown category.
This is a common production failure. The model trains on clean data, and the first missing value in live traffic crashes the service. Decide how to treat gaps during training, even if the training data has none.
Imputing before encoding
An imputer fills gaps with a chosen value. SimpleImputer supports two strategies for categorical data:
strategy="constant"with afill_valuesuch as"missing"creates an explicit category.strategy="most_frequent"replaces each gap with the most common training category.
Chaining the imputer and encoder in a pipeline makes the choice explicit and keeps it consistent between training and prediction.
import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"color": ["red", np.nan, "blue", "red"]})
cat_pipe = make_pipeline(
SimpleImputer(strategy="constant", fill_value="missing"),
OneHotEncoder(handle_unknown="ignore", sparse_output=False),
)
print(cat_pipe.fit_transform(df))
print(cat_pipe.get_feature_names_out())The columns are color_blue, color_missing, and color_red. The missing row is [0, 1, 0].
The constant strategy has one advantage over letting the encoder handle NaN. The new category exists in the training data whether or not it had gaps, as long as you keep the imputer in the pipeline. At prediction time, a gap becomes "missing", which the encoder either knows or ignores, depending on whether training had gaps.
The two approaches compare as follows.
| Approach | What the model sees | Best when | Risk |
|---|---|---|---|
| `get_dummies` default | All-zero row | Quick exploration | Same as an unseen or dropped category |
| `dummy_na=True` or encoder default | A dedicated "missing" column | Missingness may carry signal | Column exists only if training had gaps |
| Constant imputer, then encoder | A dedicated "missing" column, always planned | Production pipelines | None specific, but adds a step |
| `most_frequent` imputer, then encoder | A real category | Gaps are random and rare | Hides missingness and biases toward the mode |
Choosing a strategy
The main question is why the value is missing.
If missingness is informative, keep it visible. A blank "occupation" field may correlate with the outcome, such as customers who do not want to share details. A dedicated column lets the model learn that pattern.
If missingness is random and rare, filling with the most frequent category is reasonable. It keeps the feature matrix smaller and avoids a column that is almost always 0. Be careful with a large share of gaps, because the filled-in values then dominate the column.
If a column is mostly empty, consider dropping it. A column with 90 percent gaps adds little beyond a single "present or absent" signal.
An imputer fitted on training data learns the most frequent category from training rows only. Fitting it on the full dataset leaks test information into the model, for the same reason as fitting the encoder on all data.
Putting it in a ColumnTransformer
The usual setup gives each column group its own mini-pipeline. Categorical columns get an imputer and an encoder. Numeric columns get their own imputer and scaler.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
X = pd.DataFrame({
"city": ["Paris", "Berlin", np.nan, "Rome", "Berlin", "Rome"],
"age": [25, np.nan, 47, 51, 38, 29],
})
y = [0, 1, 0, 1, 1, 0]
preprocess = ColumnTransformer([
("cat", make_pipeline(
SimpleImputer(strategy="constant", fill_value="missing"),
OneHotEncoder(handle_unknown="ignore"),
), ["city"]),
("num", make_pipeline(
SimpleImputer(strategy="median"),
StandardScaler(),
), ["age"]),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression())])
model.fit(X, y)
new = pd.DataFrame({"city": [np.nan, "Madrid"], "age": [30, np.nan]})
print(model.predict(new))
print(model["prep"].get_feature_names_out())The new data contains a missing city and an unseen city, "Madrid". Both are handled without errors. The missing city becomes "missing", which the encoder learned. "Madrid" becomes an all-zero row because of handle_unknown="ignore". The feature names are cat__city_Berlin, cat__city_Paris, cat__city_Rome, cat__city_missing, and num__age. Uppercase letters sort before lowercase, so missing comes last.
For numeric columns, SimpleImputer(add_indicator=True) appends a binary column marking which values were filled. This is useful for numbers. For categorical columns with a constant fill, the "missing" column already does that job, so the indicator is redundant.
Common errors
- Imputing on the full dataset. Fit the imputer inside the pipeline so it learns only from training rows.
- Relying on the encoder's default for later gaps. If training had none, new gaps are unknown categories. Use an imputer or
handle_unknown="ignore". - Mixing
Noneandnp.nanin an object column and encoding it directly. Convert withdf.fillna(np.nan)or impute first, so the encoder sees one consistent missing marker. - Using
most_frequenton a column with many gaps. The model then sees a category that is far more common than it really is. - Forgetting
drop_firstwithget_dummies. A missing row and the dropped first category look identical.
Exercise
A training set has no missing values in the "plan" column. You build a pipeline with OneHotEncoder(handle_unknown="ignore") and no imputer. In production, a row arrives with plan missing. What does the model receive for that column, and what would you change to make the behavior deliberate?
Show answer
The encoder treats NaN as an unknown category, so every plan indicator column is 0 for that row. The model sees the same input it would for any unseen plan, and no error occurs. To make this deliberate, add SimpleImputer(strategy="constant", fillvalue="missing") before the encoder. Then "missing" is a planned category, or use "mostfrequent" if gaps are random. In both cases the imputer must be fitted on training data only.
Exercise
You call pd.getdummies(df, columns=["size"], dropfirst=True) on a column containing "small", "medium", "large" and some NaN values. Why can a model not tell a "large" row from a NaN row, and which option fixes it?
Show answer
Alphabetically, "large" is the first category and is dropped, so it is encoded as all zeros. Without dummyna, a NaN row is also all zeros. Adding dummyna=True creates a size_nan column, so the NaN rows are distinguishable. Alternatively, impute a "missing" category before encoding.