Sub topic 12
Preprocessing mixed columns with ColumnTransformer
This chapter assumes you know how Pipeline chains steps, how a transformer's fit and transform differ, and how to index a pandas DataFrame by column name. The examples use scikit-learn 1.2 or newer.
Why one transformer is not enough
Real tables mix column types. An age column needs scaling. A city column needs encoding as numbers. Applying StandardScaler to city fails, and one-hot encoding age creates one column per distinct age, which is useless.
ColumnTransformer solves this. You give it a list of (name, transformer, columns) triples. It fits each transformer on its own columns only, applies each one, and joins the results side by side into one feature matrix.
A first example
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [22, 35, 47, 52],
"city": ["Paris", "Rome", "Paris", "Oslo"],
})
pre = ColumnTransformer([
("num", StandardScaler(), ["age"]),
("cat", OneHotEncoder(sparse_output=False), ["city"]),
])
X_t = pre.fit_transform(df)
print(X_t.shape) # (4, 4): 1 scaled column + 3 one-hot columns
print(pre.get_feature_names_out())
# ['num__age' 'cat__city_Oslo' 'cat__city_Paris' 'cat__city_Rome']Each triple has three parts:
- A name. It must be unique. It prefixes the output feature names and lets you address the step with
set_params, for examplenum__with_mean=False. - A transformer. It can be any object with
fitandtransform, including a wholePipeline. - A column selection. It tells the ColumnTransformer which columns this transformer receives.
The output columns appear in the order of the triples, not in the original DataFrame order. The output is a NumPy array unless you ask otherwise (see below).
What happens during fit and transform
fit clones every transformer, so your original objects stay unfitted. Each clone is fitted on its own column subset. The fitted clones are stored in transformers_, and you can read them through the named_transformers_ attribute, for example pre.named_transformers_["num"].mean_.
transform slices the input by the same selections, calls each fitted transformer's transform, and concatenates the results horizontally. Nothing is re-learned at this point, so scaling statistics and category lists come from the training data only. This is the same leakage protection you get from fitting a scaler on the training set alone.
Selecting columns
The third element of a triple accepts several forms.
| Form | Example | Notes |
|---|---|---|
| List of names | `["age", "income"]` | Needs a DataFrame input. Most readable. |
| List of integer positions | `[0, 2]` | Works with NumPy arrays too. |
| Boolean mask | `[True, False, True]` | One entry per column. |
| Slice | `slice(0, 2)` | Positional. |
| Callable | `lambda df: df.columns[df.dtypes == "float64"]` | Receives the input and returns any of the above. |
| `make_column_selector` | `make_column_selector(dtype_include="number")` | Chooses by dtype or name pattern. |
Selecting by dtype is convenient when a table has dozens of columns. The next example also puts a Pipeline inside the numeric branch, so missing values are imputed before scaling.
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [22, 35, None, 52, 28, 41],
"income": [30.0, 52.0, 61.0, 75.0, 40.0, 58.0],
"city": ["Paris", "Rome", "Paris", "Oslo", "Rome", "Oslo"],
})
num_pipe = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())
pre = ColumnTransformer([
("num", num_pipe, make_column_selector(dtype_include="number")),
("cat",
OneHotEncoder(handle_unknown="ignore", sparse_output=False),
make_column_selector(dtype_exclude="number")),
])
X_t = pre.fit_transform(df)
print(X_t.shape) # (6, 5)
print(pre.get_feature_names_out())The selector runs at fit time, so the chosen columns are fixed once fitting finishes. I use dtype_exclude="number" for the categorical branch because it also catches string and category dtypes, whichever way your pandas version stores text.
The shorthand make_column_transformer((StandardScaler(), ["age"]), (OneHotEncoder(), ["city"])) generates the step names for you, such as standardscaler and onehotencoder. Explicit names are easier to use with set_params and in grid search, so prefer them in code you will tune.
The remainder: columns you did not mention
By default, remainder="drop" silently discards any column not named in a triple. This is a frequent source of confusion. A column you forgot simply disappears, with no warning.
You have two other options:
remainder="passthrough"appends the untouched columns after the transformed ones.remainder=some_transformerapplies that transformer to all leftover columns.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({"age": [22, 35, 47], "is_member": [0, 1, 1]})
pre = ColumnTransformer(
[("num", StandardScaler(), ["age"])],
remainder="passthrough",
).set_output(transform="pandas")
print(pre.fit_transform(df))
# columns: num__age, remainder__is_memberPassthrough is right for binary 0/1 flags that need no scaling. Its main drawback is that a new column added to your data later flows into the model unprocessed, so strings or missing values will break the final estimator.
Controlling the output type
ColumnTransformer returns a dense NumPy array by default. If the combined output is mostly zeros, it returns a sparse matrix instead. The deciding setting is sparse_threshold (default 0.3): the output is sparse when the overall density falls below that value. A one-hot encoder on a high-cardinality column often triggers this. Sparse output is fine for linear models and trees, but it can surprise you if you then call a method that needs a dense array. Two fixes exist:
- Set
sparse_output=Falseon theOneHotEncoder, as above. - Set
sparse_threshold=0on theColumnTransformer.
Call set_output(transform="pandas") to get a DataFrame whose column names match get_feature_names_out(). This makes debugging much easier because you can inspect what the model actually sees.
Using it inside a Pipeline
Place the ColumnTransformer as the first step, followed by the model. The result is one estimator that accepts the raw DataFrame.
import pandas as pd
from sklearn.compose import ColumnTransformer
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": [22, 35, 47, 52, 28, 41, 60, 33, 25, 58, 44, 31],
"city": ["Paris", "Rome", "Paris", "Oslo", "Rome", "Oslo",
"Paris", "Rome", "Oslo", "Paris", "Rome", "Oslo"],
"bought": [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0],
})
X, y = df[["age", "city"]], df["bought"]
clf = Pipeline([
("preprocess", ColumnTransformer([
("num", StandardScaler(), ["age"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])),
("model", LogisticRegression()),
])
print(cross_val_score(clf, X, y, cv=3).mean())Passing the whole pipeline to cross_val_score refits the scaler and encoder on each training fold. That keeps validation rows out of preprocessing.
Common errors and how to read them
- "Expected 2D array, got 1D array." You wrote
"age"instead of["age"]. A bare string selects a 1D Series. Only transformers that expect 1D input, such asCountVectorizerfor a text column, want the bare string. - "Found unknown categories ... during transform." A category appeared at prediction time that was absent from training. Set
handle_unknown="ignore"on theOneHotEncoder. An unseen value then becomes a row of zeros in that column's output. - "A given column is not a column of the dataframe." The data passed to
predicthas different column names than the data passed tofit. Names are checked, so keep the schema identical. - Wrong column count or order at predict time with NumPy input. Integer selections depend on position. If you reorder columns, the wrong data goes to each transformer. Prefer names.
- A model that ignores a feature you expected. Check
remainder. With the default"drop", an unlisted column never reaches the model. - NaN reaching the encoder or model. Add a
SimpleImputerinside each branch. Imputing outside the transformer, on the full dataset, leaks information from the test rows.
Exercise
A ColumnTransformer is built with [("num", StandardScaler(), ["age"])] and nothing else. The input DataFrame has columns age, city and is_member. How many columns does fit_transform return, and what single argument would make it return all three original columns?
Show answer
It returns 1 column, the scaled age, because the default remainder="drop" discards city and is_member. Adding remainder="passthrough" appends the two untouched columns, giving 3 columns. Note that city would still be a string column, so a downstream model would fail unless it was encoded.
Exercise
You call ColumnTransformer([("num", StandardScaler(), "age")]).fit(df) and get an error about a 1D array. What is the one-character-pair fix?
Show answer
Wrap the column name in a list: ["age"]. A scalar string selects a 1D Series, but StandardScaler needs a 2D input with one column per feature.