Sub topic 5
Different preprocessing for different columns
Real tables mix column types. Numbers need imputing and scaling. Categories need imputing and encoding. Text needs a vectorizer. A plain Pipeline sends every column through every step, so it can't express this. ColumnTransformer can: it applies a different transformer to each group of columns and joins the results into one feature matrix.
This chapter assumes you can build a Pipeline with make_pipeline. It also assumes you know what fit and transform do, and you can handle a pandas DataFrame. Cross-validation and tuning of the result come in later chapters.
The core idea
A ColumnTransformer takes a list of (name, transformer, columns) tuples. For each tuple it does three things:
- It selects the named columns from the input.
- It fits the transformer on them during
fit. - It applies the transformer during
transform.
It then concatenates the outputs side by side, in the order you listed them.
Each branch is usually a small Pipeline. The branches are independent: the numeric imputer never sees the city column. Every branch is fitted on training data only, so the leakage protection from the earlier chapters still holds.
A complete example
The table below has two numeric columns with gaps and one categorical column with a gap. Missing values are np.nan, which is what SimpleImputer looks for by default.
import numpy as np
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, np.nan, 47, 51, 38],
"income": [40000, 52000, 61000, np.nan, 88000, 57000],
"city": ["Oslo", "Bergen", np.nan, "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 are num__age, num__income, cat__city_Bergen and cat__city_Oslo. The prefix is the name you gave the tuple, which keeps names unique when two branches produce a column with the same name.
The whole ColumnTransformer is one step of the outer pipeline. When you call model.predict(new_df), the transformer selects the same columns by name and applies the already-fitted branches.
Choosing columns
The third element of each tuple can take several forms.
| Selector | Example | Notes |
|---|---|---|
| List of names | `["age", "income"]` | Needs a DataFrame. Most readable. |
| Single name | `"age"` | Passes a 1D Series. Needed by text vectorizers. |
| Integer positions | `[0, 1]` or `slice(0, 2)` | Works for NumPy arrays and DataFrames. |
| Boolean mask | `[True, True, False]` | One entry per column. |
| Callable | `lambda df: df.columns[df.dtypes == "float64"]` | Receives the input and returns any form above. |
| `make_column_selector` | `make_column_selector(dtype_include="number")` | Selects by dtype or by name pattern. |
Selecting by dtype avoids hard-coding column lists. The next example also shows remainder and set_output.
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.preprocessing import StandardScaler, OneHotEncoder
df = pd.DataFrame({
"age": [25, 32, 41, 47],
"income": [40000, 52000, 61000, 88000],
"city": ["Oslo", "Bergen", "Oslo", "Bergen"],
"visits": [3, 0, 7, 2],
})
ct = ColumnTransformer(
[
("num", StandardScaler(), ["age", "income"]),
("cat",
OneHotEncoder(handle_unknown="ignore", sparse_output=False),
make_column_selector(dtype_exclude="number")),
],
remainder="passthrough",
verbose_feature_names_out=False,
)
ct.set_output(transform="pandas")
out = ct.fit_transform(df)
print(out.columns.tolist())
# A city never seen during fit gets all zeros in the one-hot columns.
new = pd.DataFrame({
"age": [30], "income": [50000], "city": ["Tromso"], "visits": [1],
})
print(ct.transform(new)[["city_Bergen", "city_Oslo"]].to_numpy())The first print shows ['age', 'income', 'city_Bergen', 'city_Oslo', 'visits']. The second shows [[0. 0.]]. Four details in this example matter:
- The
catbranch selects "every column that is not a number". It would pick up new string columns automatically, which is convenient but also means a stray text column silently becomes one-hot features. remainder="passthrough"keepsvisits, which no tuple selected. It is placed after all the listed branches.verbose_feature_names_out=Falsedrops thenum__andcat__prefixes. This is only safe when no two branches produce the same name. If they do,fitraises an error.set_output(transform="pandas")returns a DataFrame with column names instead of a bare array. It requires dense output from every branch, which is why the encoder usessparse_output=False.
What happens to unlisted columns
By default remainder="drop". Any column not selected by a tuple is silently discarded. This is a common source of "my model ignores a feature" bugs. There are three options:
"drop"discards unlisted columns. This is the default."passthrough"appends them unchanged. They are not scaled or imputed, so a passthrough column with missing values will make many estimators fail.- An estimator, such as
StandardScaler(), applies that transformer to all unlisted columns. It appears in the fitted attributes asremainder.
A transformer slot can also hold the strings "drop" or "passthrough". For example, ("skip_id", "drop", ["customer_id"]) makes the exclusion explicit and visible in the code.
The shorthand: make_column_transformer
make_column_transformer generates step names for you, in the same way make_pipeline does. The arguments are (transformer, columns) pairs.
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
prep = make_column_transformer(
(StandardScaler(), ["age", "income"]),
(OneHotEncoder(handle_unknown="ignore"), ["city"]),
)
print(prep.transformers)The generated names are standardscaler and onehotencoder. Use the explicit form when you plan to tune parameters, because you will want to choose and remember the names yourself.
One column versus a list of one column
The shape you pass depends on the form of the selector. A string such as "review" hands the transformer a 1D Series. A list such as ["review"] hands it a 2D DataFrame with one column.
- Text vectorizers such as
TfidfVectorizerexpect 1D input, so they need"review". - Almost everything else, including scalers and encoders, expects 2D input, so they need
["age"].
Passing the wrong form produces a shape error. The message usually says "Expected 2D array, got 1D array" or "iterable over raw text documents expected".
Details that bite
Column order and names at predict time
When you fit on a DataFrame and select by name, ColumnTransformer records the column names. At transform time it checks that the same names are present. Extra columns are fine, and order does not matter. A missing column raises an error. This is a strength of name-based selection.
When you select by integer position, the transformer trusts the order. If the columns arrive shuffled, the model is silently wrong. If you fit on a NumPy array, positions are all you have, so keep the order fixed.
Sparse versus dense output
OneHotEncoder returns a sparse matrix by default. ColumnTransformer combines the branch outputs and decides whether the final result is sparse. It uses the sparse_threshold parameter, which defaults to 0.3. If the overall density of the combined matrix is below the threshold, the result is sparse. Otherwise it is dense.
This usually works without any action from you. Some estimators, such as HistGradientBoostingClassifier in older versions, or a GaussianNB, need dense input. If you see "A sparse matrix was passed, but dense data is required", set sparse_threshold=0 on the transformer, or use sparse_output=False on the encoder.
Unseen categories
OneHotEncoder raises an error on a category that was not present during fit. In production that is rarely what you want. Set handle_unknown="ignore" so new categories encode as all zeros, as the second example showed. For a high-cardinality column you can also set min_frequency to group rare categories together.
Order of imputation and encoding
Impute before you encode. OneHotEncoder treats np.nan as its own category by default, so a missing city becomes its own indicator column. Both approaches are valid: imputing says "assume the most common value", while leaving the gap says "missing is informative". Choose deliberately.
Parallelism and weights
n_jobs fits the branches in parallel. This helps when a branch is expensive, such as a text vectorizer on a large column, and does little for cheap scalers. transformer_weights={"num": 2.0} multiplies the output of a named branch. This is rarely needed, but it can matter for distance-based models.
Inspecting the result
The fitted transformer exposes the branches in several ways:
ct.named_transformers_["num"]returns the fitted branch, which is aPipelinein the first example. You can then index into it:ct.named_transformers_["cat"]["onehot"].categories_lists the learned categories.ct.transformers_is the list of fitted tuples. It also includes theremainderentry.ct.get_feature_names_out()gives the output names, as used in the first example.
Use named_transformers_ for fitted objects. The transformers attribute holds the unfitted originals you passed in.
Common mistakes
- Fitting on the whole dataset first. Calling
ct.fit_transform(df)on all data and then splitting reintroduces the leakage this tutorial exists to prevent. Put theColumnTransformerinside the pipeline and fit the pipeline on the training split only. - Scaling one-hot columns. Passing every column through
StandardScalerafter encoding is unnecessary. It also makes the binary columns harder to read. - Mixed dtypes inside one column. A column of numbers and strings becomes
objectdtype and lands in the wrong branch under dtype selection. Clean it before the pipeline. - Duplicate output names. With
verbose_feature_names_out=False, two branches that emit the same name makefitfail. Leave the prefixes on unless you know the names are unique.
Exercise
A pipeline contains a ColumnTransformer with ("num", StandardScaler(), ["age", "income"]) and ("cat", OneHotEncoder(), ["city"]), and the default remainder. The training DataFrame also has a numeric column "visits". The model trains with no errors, but "visits" has no influence on predictions. Why, and how do you fix it in two different ways?
Show answer
The default remainder="drop" discards any column that no tuple selects, so "visits" never reaches the classifier. Fix 1: add "visits" to a transformer tuple, for example to the numeric list, so it is scaled with the others. Fix 2: set remainder="passthrough" to append it unchanged. This only works if "visits" has no missing values and the model does not need it scaled. Passing the column through an explicit tuple is usually clearer.
Exercise
You fit a ColumnTransformer with OneHotEncoder() on training data. A month later, the model fails on new data with an error about an unknown category "Tromso". What parameter prevents this error, and what will the encoded city columns look like for that row?
Show answer
Set handle_unknown="ignore" on the OneHotEncoder. A city that was not seen during fit is then encoded as all zeros in the one-hot columns, so the row has no city indicator set. The other columns are unaffected.