Sub topic 7
Combining imputers with ColumnTransformer and Pipeline
This chapter assumes you know the SimpleImputer strategies from earlier chapters, the fit/transform pattern, and why you fit on training data only. Here you will put those pieces into one object that handles numeric and categorical columns correctly.
Why one imputer is not enough
A single SimpleImputer applies one strategy to every column it sees. Real tables mix column types. A median suits age, but it fails on a text column such as city. Calling fit_transform separately on each group and stacking the results by hand is error-prone, and it makes leakage easy to introduce.
Two scikit-learn tools solve this:
Pipelinechains steps in order. Each step's output feeds the next, and the last step can be a model.ColumnTransformerapplies different transformers to different columns, then joins the results side by side.
The structure
Each column group gets its own small pipeline: impute first, then scale or encode. Those group pipelines sit inside a ColumnTransformer. The ColumnTransformer sits inside an outer Pipeline that ends with the model.
A complete example
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
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [25, np.nan, 40, 31, 52, np.nan],
"income": [40000, 52000, np.nan, 61000, 75000, 48000],
"city": ["Oslo", "Rome", np.nan, "Oslo", "Rome", "Oslo"],
})
y = [0, 1, 0, 1, 1, 0]
numeric = ["age", "income"]
categorical = ["city"]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), numeric),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), categorical),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression()),
])
model.fit(df, y)
print(model.predict(df))Each ColumnTransformer entry is a tuple of (name, transformer, columns). The name is a label you choose. The transformer here is itself a Pipeline. The columns are a list of column names.
What happens during fit
Calling model.fit(df, y) runs these steps:
- The
ColumnTransformerslices out the numeric columns and fits the median imputer on them. - It passes the imputed numbers to the scaler, which learns means and standard deviations from the already-filled data.
- It does the same for
city: the imputer learns the most frequent value, and the encoder learns the categories. - It joins the outputs into one matrix, and the classifier trains on it.
Calling model.predict(new_df) reuses every learned value. Nothing is refit. Missing ages in new data get the training median, and a missing city gets the training mode. This is the leakage protection from the previous chapter, applied automatically.
The same property holds inside cross-validation. When you pass model to cross_val_score or GridSearchCV, scikit-learn clones the whole pipeline and refits it on each training fold. Statistics from the validation fold never reach the imputer.
Inspecting learned values
Fitted steps are reachable by name, so you can still read statistics_:
prep = model.named_steps["prep"]
num_imputer = prep.named_transformers_["num"].named_steps["impute"]
cat_imputer = prep.named_transformers_["cat"].named_steps["impute"]
print(num_imputer.statistics_) # median of age (35.5) and income (52000.0)
print(cat_imputer.statistics_) # ['Oslo']Append this to the example above. Note the trailing underscore on named_transformers_. Without it you get the unfitted transformers.
Why impute before scaling and encoding
Order matters. If you scale first, StandardScaler ignores NaN when computing its statistics, so the NaN passes through. The imputer then fills in values on the original scale, which now sit inconsistently next to scaled data. Imputing first means every later step sees complete, consistent values.
For categorical columns, imputing before OneHotEncoder makes the choice explicit: a missing city becomes the most common city. If you would rather keep "missing" as its own category, use strategy="constant" with fill_value="missing" instead.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| A column vanishes from the output | `ColumnTransformer` drops columns you did not list (`remainder="drop"` is the default) | List the column, or set `remainder="passthrough"` |
| NaN still present, then the model raises an error | A column was passed through without an imputer | Add it to a group with an imputer |
| `ValueError` about strings and the median | A text column was placed in the numeric group | Move it to the categorical group |
| Results look too good in validation | Imputation was done on the full dataset before splitting | Put the imputer inside the pipeline |
Choosing columns by type
Hard-coded lists are fine for small tables. For wide tables, make_column_selector picks columns by dtype:
from sklearn.compose import make_column_selector as selector
numeric = selector(dtype_include="number")
categorical = selector(dtype_exclude="number")Use these in place of the lists in the ColumnTransformer. The selectors run at fit time, so the chosen columns depend on the training frame's dtypes. Check that those dtypes are what you expect.
Exercise
You build a ColumnTransformer with a median imputer for ["age", "income"] and a most_frequent imputer for ["city"]. Your DataFrame also has a numeric column "tenure" with missing values that you forgot to list. The default settings are unchanged. What happens to "tenure", and how do you keep it imputed?
Show answer
With the default remainder="drop", "tenure" is silently removed from the output, so the model never sees it. To keep it imputed, add "tenure" to the numeric list. Setting remainder="passthrough" would keep the column but leave its NaN values unfilled, and most estimators would then raise an error.