Sub topic 12
Preprocessing mixed columns with ColumnTransformer
This chapter assumes you know Pipeline, the fit/transform convention, and basic pandas DataFrames. You should also know why numeric and categorical features need different preprocessing.
The problem
Real tables mix column types. A StandardScaler suits an age column but is meaningless for a city name. A OneHotEncoder suits the city but would turn every age into its own column. A plain Pipeline applies each step to all columns, so it cannot handle both at once.
ColumnTransformer solves this. It applies different transformers to different columns, then joins the results side by side into one feature matrix.
How it works
You give it a list of (name, transformer, columns) tuples. On fit, each transformer learns from its own columns of the training data only. On transform, each applies what it learned, and the outputs are concatenated in the order you listed them.
A complete example
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [22, 35, 47, 52, 28, 41, 60, 33],
"city": ["Paris", "Rome", "Paris", "Oslo", "Rome", "Oslo", "Paris", "Rome"],
"bought": [0, 1, 1, 0, 0, 1, 1, 0],
})
X = df[["age", "city"]]
y = df["bought"]
preprocess = ColumnTransformer([
("num", StandardScaler(), ["age"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
clf = Pipeline([
("preprocess", preprocess),
("model", LogisticRegression()),
])
clf.fit(X, y)
print(clf.predict(X.iloc[:3]))
new_row = pd.DataFrame({"age": [30], "city": ["Berlin"]})
print(clf.predict(new_row))
print(preprocess.get_feature_names_out())The Pipeline is a single estimator, so clf.fit and clf.predict behave like any model. The scaler and encoder are fitted only on the data passed to fit.
The second prediction uses a city the encoder never saw. With handle_unknown="ignore", it becomes a row of zeros in the city columns. Without that setting, transform raises an error.
get_feature_names_out() returns names such as num__age and cat__city_Oslo. The prefix is the step name you chose.
Choosing columns
Columns can be listed by name, as above. You can also pass integer positions, or a selector such as make_column_selector(dtype_include="number"). A selector picks columns by dtype at fit time, which helps with wide tables.
What happens to the other columns
By default remainder="drop" discards any column you did not list. This is easy to miss. Set remainder="passthrough" to keep unlisted columns unchanged, or give a transformer to process them.
| Setting | Effect on unlisted columns |
|---|---|
| `remainder="drop"` (default) | Removed from the output |
| `remainder="passthrough"` | Appended unchanged |
| `remainder=some_transformer` | Transformed together as a group |
Common errors
- A column name in the transformer list that is missing from the DataFrame raises a
ValueError. Check spelling and thatXstill contains the column. - Selecting columns by name needs a DataFrame input. With a NumPy array, use integer positions.
- The output may be sparse or dense, depending on
sparse_threshold. Models that need dense input may fail on sparse input, so checktype(output)if you see that error. - Forgetting that
remainderdrops columns silently, then wondering why a feature has no effect.
Exercise
You add a "income" column to X but do not list it in the ColumnTransformer, which uses the default settings. Will the model use income? How do you make it use income unscaled?
Show answer
No. The default remainder="drop" removes unlisted columns, so income never reaches the model. Set remainder="passthrough" to append it unchanged, or add a ("inc", StandardScaler(), ["income"]) tuple to scale it.