Sub topic 5
Different preprocessing for different columns
Real tables mix column types. Numeric columns need imputing and scaling. Categorical columns need imputing and encoding. This chapter shows how ColumnTransformer applies a separate preprocessing chain to each group of columns and passes the combined result to a model.
This chapter assumes you know Pipeline, the fit/transform API, and basic pandas. Pipelines were covered in the previous chapter.
The problem
A single StandardScaler cannot handle a text column such as a city name. A single OneHotEncoder would be wrong for age or income. You need to route each column to the right transformer and then join the outputs side by side.
ColumnTransformer does this routing. You give it a list of (name, transformer, columns) tuples. It fits each transformer on its own columns, transforms them, and concatenates the results into one feature matrix.
A complete example
Each branch is itself a Pipeline, so a column group can have several steps. The whole ColumnTransformer then becomes the first step of the outer pipeline.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
df = pd.DataFrame({
"age": [25, 32, None, 47, 51, 38],
"income": [40000, 52000, 61000, None, 88000, 57000],
"city": ["Oslo", "Bergen", None, "Oslo", "Bergen", "Oslo"],
})
y = [0, 0, 1, 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(max_iter=1000)),
])
model.fit(df, y)
# All steps except the final estimator, then the output column names.
print(model[:-1].get_feature_names_out())The printed names look like num__age, num__income, cat__city_Bergen, and cat__city_Oslo. The prefix is the transformer name you chose. The one-hot columns carry the category value after the original column name.
How it works
fitreceives the full DataFrame. For each tuple, it selects the listed columns and fits that transformer on them.transformapplies each fitted transformer to its columns.- The outputs are stacked horizontally, in the order you listed the tuples.
Because the transformer sits inside the outer Pipeline, all of this is refit on the training portion only during cross-validation. This keeps the leakage protection from earlier chapters.
Choosing columns
You can name columns with a list of strings, as above. This is the clearest option when your input is a DataFrame. You can also use integer positions, boolean masks, or a selector function.
make_column_selector picks columns by dtype, which avoids hard-coding names:
from sklearn.compose import make_column_selector
selector = make_column_selector(dtype_include="number")
print(selector(df))This prints ['age', 'income']. Selecting by dtype is convenient, but object columns that hold numbers as text will be missed. Check the dtypes before you rely on it.
Common errors
- Dropped columns. By default
remainder="drop", so any column you do not list disappears silently. Setremainder="passthrough"to keep unlisted columns unchanged, or list every column explicitly. - Unseen categories. Without
handle_unknown="ignore",OneHotEncoderraises an error when prediction data contains a city not seen in training. With it, the unseen city becomes a row of zeros. - Missing values in categorical columns.
OneHotEncodercan treat missing values as their own category, but imputing first, as above, keeps the behavior explicit. - A single string instead of a list. Writing
"city"selects a 1D column, which most transformers reject. Write["city"]to get a 2D table. - Wrong input type at prediction time. The transformer selects by column name, so pass a DataFrame with the same column names. A bare NumPy array fails.
Naming for later chapters
The names prep, num, and cat matter. Parameter search addresses nested parameters with double underscores, for example prep__num__impute__strategy. Short, consistent names make those strings easier to write.
Exercise
You add a numeric column "tenure" to your DataFrame but forget to add it to the numeric list. The model trains without errors. What happened to "tenure", and what are two ways to prevent this?
Show answer
The ColumnTransformer dropped it, because remainder defaults to "drop". Prevent it by adding "tenure" to the numeric list, or by setting remainder="passthrough" so unlisted columns pass through unchanged. Checking get_feature_names_out() also reveals the missing column.
Exercise
Why does ("cat", encoder, "city") often fail, while ("cat", encoder, ["city"]) works?
Show answer
A bare string selects a 1D Series. Transformers such as OneHotEncoder expect a 2D table, which a list of column names produces.