Sub topic 7
Combining imputers with ColumnTransformer and Pipeline
This chapter assumes you know how SimpleImputer works (fit, transform, statistics_). It also assumes you can use pandas DataFrames and understand why you fit preprocessing on training data only. By the end you will build one object that imputes, scales and encodes a mixed-type table. You will fit that object safely inside cross-validation, inspect what it learned, and debug the usual mistakes.
Why one imputer is not enough
A real table mixes column types. age and income are numbers, and city is text. A single SimpleImputer cannot serve both, for two reasons:
- The
meanandmedianstrategies only work on numeric data. Themost_frequentandconstantstrategies work on both, but the right choice differs per column. - Imputation is rarely the last step. Numeric columns usually need scaling afterwards. Categorical columns need encoding. These later steps are also column-specific.
You could split the DataFrame by hand, transform each part, and stack the results with NumPy. That approach has three weaknesses:
- It is easy to get the column order wrong.
- You must repeat the same splitting code at prediction time.
- It breaks cross-validation, because the fill values would be learned outside the loop.
Two scikit-learn tools remove this work:
Pipelinechains steps so that the output of one step is the input of the next. Callingfitfits every step in order on the training data.ColumnTransformerapplies different transformers to different columns and concatenates the results side by side.
You nest them. Each column group gets its own small Pipeline, a ColumnTransformer routes columns to those pipelines, and an outer Pipeline attaches the final model.
The structure
The diagram shows the layout of the example below.
A ColumnTransformer takes a list of (name, transformer, columns) tuples. The name is a label you choose. The transformer can be a single estimator or a Pipeline. The columns say which part of the input that transformer receives.
A complete worked example
The following code builds the whole structure and fits it. It also shows prediction on a row where every value is missing.
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))
new_row = pd.DataFrame({"age": [np.nan], "income": [np.nan], "city": [np.nan]})
print(model.predict(new_row))Here is what happens when you call model.fit(df, y):
- The outer pipeline calls
fit_transformonprep, then fitsclfon the result. ColumnTransformerslicesdf[["age", "income"]]and sends it into thenumpipeline. The median imputer learns one median per column. The scaler then learns a mean and standard deviation from the already-imputed values.- It slices
df[["city"]]and sends it into thecatpipeline. The imputer learns the most frequent city. The encoder learns the categories. - The two outputs are joined column by column, so the classifier receives four columns:
age,income,city_Osloandcity_Rome.
At prediction time the same learned values are reused. The row with no data at all becomes the median age, the median income and the most frequent city. No fitting happens during predict.
The order inside the numeric pipeline matters. If you scaled first, StandardScaler would ignore NaN when computing its statistics and pass NaN through. The imputer then fills values that are on the wrong scale. Impute first, then scale.
Inspecting what each step learned
A fitted pipeline keeps every learned attribute. You reach them by name:
model.named_steps["prep"]returns the fittedColumnTransformer..named_transformers_["num"]returns the fitted numeric pipeline..named_steps["impute"]returns the fitted imputer inside it.
The next block fits a pipeline on the same data. It reads the fill values and the output column names, and uses set_output to get a DataFrame back.
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, 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"],
})
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
]), ["city"]),
])
preprocess.set_output(transform="pandas")
out = preprocess.fit_transform(df)
num_imputer = preprocess.named_transformers_["num"].named_steps["impute"]
cat_imputer = preprocess.named_transformers_["cat"].named_steps["impute"]
print(num_imputer.statistics_) # [ 35.5 52000. ]
print(cat_imputer.statistics_) # ['Oslo']
print(out.columns.tolist())
# ['num__age', 'num__income', 'cat__city_Oslo', 'cat__city_Rome']
print(out.isna().sum().sum()) # 0The medians are 35.5 for age (from 25, 31, 40, 52) and 52000 for income. "Oslo" appears three times and "Rome" twice, so Oslo is the most frequent value.
The prefixes num__ and cat__ come from the names you chose in the ColumnTransformer. Pick short, meaningful names, because they appear in feature importances, coefficient plots and error messages.
Imputation inside cross-validation
The earlier chapter on leakage explained why imputers must be fitted on training data only. A pipeline enforces this for you. When you pass the whole pipeline to a cross-validation function, scikit-learn clones it for each fold. It fits the clone, imputer included, on that fold's training rows. It then scores on the held-out rows using the training fold's statistics.
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.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [25, np.nan, 40, 31, 52, np.nan, 29, 45, 38, np.nan, 60, 33],
"income": [40000, 52000, np.nan, 61000, 75000, 48000,
39000, 70000, np.nan, 55000, 82000, 43000],
"city": ["Oslo", "Rome", np.nan, "Oslo", "Rome", "Oslo",
"Oslo", "Rome", "Rome", np.nan, "Rome", "Oslo"],
})
y = [0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), ["age", "income"]),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), ["city"]),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression())])
scores = cross_val_score(model, df, y, cv=3)
print(scores) # three accuracy values, one per fold
print(scores.mean())The leaky alternative is to call SimpleImputer().fit_transform(X) on the full table and then run cross_val_score on the result. Every fold's medians would then include rows from that fold's validation set, and the score would be slightly optimistic. With a pipeline you cannot make this mistake, because the imputer is just another step that gets refitted.
The same applies to GridSearchCV. You can tune imputer settings by using the step path in the parameter grid:
param_grid = {
"prep__num__impute__strategy": ["mean", "median"],
"clf__C": [0.1, 1.0, 10.0],
}Each __ descends one level: the pipeline step prep, the transformer num, the step impute, then the parameter strategy. Passing param_grid to GridSearchCV(model, param_grid, cv=3) then treats the imputation strategy as a hyperparameter chosen by validation score.
Selecting columns without typing every name
Hard-coded lists are clear but become tedious for wide tables. make_column_selector picks columns by dtype or by name pattern at fit time:
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), make_column_selector(dtype_include="number")),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), make_column_selector(dtype_exclude="number")),
])The selector reads dtypes from the DataFrame passed to fit, so it works only with DataFrames. It also depends on pandas assigning sensible dtypes. A numeric column read from a CSV that contains the text "?" becomes object, and the selector would send it to the categorical branch. Check df.dtypes before relying on a selector.
Common errors and how to read them
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError: Expected 2D array, got 1D array` | You passed a column as a string (`"age"`) instead of a list (`["age"]`). A bare string selects a Series. | Wrap the name in a list. |
| `ValueError: Cannot use mean strategy with non-numeric data` | A text column reached a `mean` or `median` imputer. | Route it to a `most_frequent` or `constant` imputer, or fix its dtype. |
| Columns are missing from the output | `ColumnTransformer` drops any column you did not list (`remainder="drop"` is the default). | Add the column to a transformer, or set `remainder="passthrough"`. Passthrough columns are not imputed, so NaN can still reach the model. |
| `ValueError: A given column is not a column of the dataframe` at predict time | The new DataFrame lacks a column that existed at fit time. Columns are matched by name. | Supply all training columns, even if they are entirely NaN. |
| `Input X contains NaN` from the classifier | Some column is not covered by any imputing branch, often through `remainder="passthrough"`. | List every column that can contain NaN in an imputing pipeline. |
| Scores differ from a manual run | Statistics are learned per training fold, not on the whole data. | This is correct behavior, not a bug. |
Three points are worth noting:
- Output order.
ColumnTransformerconcatenates in the order of your transformer list, not the original column order. Useget_feature_names_out()orset_outputto track names, and never assume positions. - A column in two branches. You may list the same column in two transformers. This is legal and useful, for example median-imputing
agein one branch and binning it in another. Remember that both outputs are kept. - Indicator columns shift the width. If you set
add_indicator=Trueon an imputer inside a branch, that branch emits extra columns. Downstream steps in the same branch, such as a scaler, will also scale those 0/1 columns. This is harmless for most models, but it surprises people reading the output.
Design choices
You can also pass SimpleImputer straight into a ColumnTransformer without a nested pipeline. Use that when no later step is needed in the branch. Nest a Pipeline when the branch has two or more steps, because the order of those steps is part of the model.
A shortcut exists: make_pipeline and make_column_transformer generate step names automatically, such as simpleimputer-1. They save typing, but the generated names make GridSearchCV parameter paths longer and harder to read. For a model you will tune or maintain, explicit names are worth the extra lines.
Finally, keep the final estimator in the same Pipeline as the preprocessing. Then you save and load one object with joblib, and deployed predictions apply the exact imputation values learned at training time.
Exercise
In the worked example, you replace ("impute", SimpleImputer(strategy="median")) in the numeric branch with ("scale", StandardScaler()) first and ("impute", ...) second. The model still runs. Why is the order still a mistake, and what does the scaler do with NaN?
Show answer
StandardScaler ignores NaN when computing its mean and standard deviation, and it passes NaN through unchanged. The imputer then fills each NaN with the median of the already-scaled column, which is a value on the scaled range. The result is similar to imputing first, but the scaler's mean and variance were computed without the missing rows. They are then not recomputed after imputation, so the final column is no longer centered at 0 with unit variance. Imputing first means the scaler sees the filled values, so the learned statistics describe the data the model actually receives.
Exercise
Write the param_grid keys needed to let GridSearchCV choose between "most_frequent" and "constant" for the categorical imputer in the pipeline Pipeline([("prep", ColumnTransformer([... ("cat", Pipeline([("impute", ...), ("onehot", ...)]), ["city"])])), ("clf", ...)]). Which extra key is needed so the constant strategy fills with the string "missing"?
Show answer
Use "prep__cat__impute__strategy": ["most_frequent", "constant"] and "prep__cat__impute__fill_value": ["missing"]. The path follows pipeline step prep, transformer cat, step impute, then the parameter name. When the strategy is most_frequent, fill_value is ignored, so one value in the grid is enough.
Exercise
A teammate fits SimpleImputer(strategy="median").fit_transform(X) on all rows, then calls cross_val_score(LogisticRegression(), X_imputed, y, cv=5). What goes wrong, and how do you fix it with a pipeline?
Show answer
Each fold's validation rows contributed to the medians used to fill training rows, and the training medians were used to fill validation rows, so information crosses the fold boundary and the score is optimistic. Fix it with model = Pipeline([("impute", SimpleImputer(strategy="median")), ("clf", LogisticRegression())]) and cross_val_score(model, X, y, cv=5), where X still contains NaN. The imputer is then refitted on the training portion of each fold.