Sub topic 3
Combining Imputers with ColumnTransformer and Pipeline
Assume you know NumPy, pandas, and the scikit-learn fit/transform pattern. A ColumnTransformer applies different preprocessing to selected columns. A Pipeline connects preprocessing to a model and refits every step during training.
Combining imputers with ColumnTransformer and Pipeline
Numeric and categorical columns usually need different imputers. This example uses the median for numeric values and the most common value for the categorical column.
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
X = 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([
("numeric", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), numeric),
("categorical", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), categorical),
])
model = Pipeline([
("preprocess", preprocess),
("classifier", LogisticRegression()),
])
model.fit(X, y)
print(model.predict(X))
print(model.named_steps["preprocess"].get_feature_names_out())The pipeline prevents preprocessing from being accidentally skipped. During cross-validation, each imputer learns values from that fold's training data only.
Keeping the missingness signal
Imputation hides which values were absent. Sometimes absence itself carries information. Set add_indicator=True to append binary columns. Each indicator contains 1 when the corresponding original value was missing.
Edge cases: empty columns, dtypes, and names
- An all-missing column may be dropped. Set
keep_empty_features=Truewhen the column must remain. np.nanworks naturally with numeric data. For another sentinel, such as-1, passmissing_values=-1.- Categorical data should use a compatible strategy, such as
most_frequentorconstantwith a stringfill_value. - Inspect transformed names with
get_feature_names_out()after aColumnTransformer.
When SimpleImputer is not enough
Simple imputation treats each column independently. It cannot infer that one feature's value predicts another feature's missing value. Consider KNNImputer when nearby rows are meaningful, or IterativeImputer when relationships among features are strong. Compare these methods with cross-validation inside a pipeline.
Exercise
Why should an imputer be inside the pipeline rather than fitted on the complete dataset?
Show answer
The pipeline learns fill values separately from each training split, preventing test-set information from leaking into preprocessing.