Sub topic 12
Putting it in a ColumnTransformer and Pipeline
This chapter assumes you can use OneHotEncoder on its own, including the handle_unknown option. It also assumes you know how to split data into training and test sets, and that you can read a pandas DataFrame. Here you combine encoding with the rest of your preprocessing so that one object can be fitted, evaluated and reused without leaking information.
Why a single object matters
Real tables mix column types. A typical frame has text categories, numbers that need scaling, and gaps in both. Each type needs a different transformation, and every transformation that learns something from data must learn it from the training rows only.
You could do this by hand. You would call get_dummies on one slice, scale another slice, and glue the pieces together with pd.concat. That approach has three recurring failures:
- The test set produces different dummy columns than the training set, so the matrix shapes disagree.
- A scaler or imputer is fitted on all the data before splitting, which leaks test statistics into training.
- Column order changes between training and serving, and the model silently reads the wrong columns.
scikit-learn solves these with two tools. A ColumnTransformer routes different columns to different transformers. A Pipeline chains the combined preprocessing and a model into one estimator.
The working model
A ColumnTransformer takes a list of (name, transformer, columns) tuples. When you call fit, each transformer is fitted on its own columns only. When you call transform, each transformer runs on its columns, and the outputs are concatenated side by side in the order you listed them.
A Pipeline calls fit_transform on every step except the last, then fit on the final estimator. At prediction time it calls transform on each step and predict on the last. So when you call model.fit(X_train, y_train), every learned quantity comes from X_train. These quantities are the category lists, the means, the standard deviations and the model weights.
A minimal example
This is the smallest useful version. One column is one-hot encoded and one is scaled.
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
X = pd.DataFrame({
"city": ["Paris", "Berlin", "Paris", "Rome", "Berlin", "Rome"],
"age": [25, 32, 47, 51, 38, 29],
})
y = [0, 1, 0, 1, 1, 0]
preprocess = ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
("num", StandardScaler(), ["age"]),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression()),
])
model.fit(X, y)
print(model.predict(X))The step names (cat, num, prep, clf) are labels you choose. They matter later for inspecting the fitted object and for hyperparameter search, where you address a setting as prep__cat__drop.
A realistic example with missing values
Real columns contain gaps. OneHotEncoder treats NaN as just another category by default, which is often acceptable. When you want explicit control, put an imputer in front of the encoder. A transformer slot in a ColumnTransformer can itself be a Pipeline, so each column group gets its own chain.
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.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
X = pd.DataFrame({
"city": ["Paris", "Berlin", "Paris", "Rome", "Berlin", "Rome", "Paris", "Berlin"],
"plan": ["basic", "pro", np.nan, "pro", "basic", "basic", "pro", "basic"],
"age": [25, 32, 47, 51, np.nan, 29, 41, 36],
})
y = [0, 1, 0, 1, 1, 0, 1, 0]
cat_cols = ["city", "plan"]
num_cols = ["age"]
cat_pipe = Pipeline([
("impute", SimpleImputer(strategy="constant", fill_value="missing")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
])
num_pipe = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
preprocess = ColumnTransformer([
("cat", cat_pipe, cat_cols),
("num", num_pipe, num_cols),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression()),
])
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model.fit(X_train, y_train)
new_rows = pd.DataFrame({
"city": ["Madrid"],
"plan": ["pro"],
"age": [30],
})
print(model.predict(new_rows))
print(model.named_steps["prep"].get_feature_names_out())
scores = cross_val_score(model, X, y, cv=2)
print(scores)Three things happen here that a hand-built version would get wrong:
- The median for
ageand the category lists forcityandplancome fromX_trainonly. "Madrid"was never seen during fitting. Because ofhandle_unknown="ignore", its city columns are all zeros and prediction still works.cross_val_scoreclones and refits the whole pipeline on each training fold. The encoder and scaler therefore never see the validation fold during fitting. This is why you pass the pipeline, not pre-transformed data, to cross-validation.
The dataset is far too small to give meaningful scores. It only demonstrates the mechanics.
Inspecting the output
get_feature_names_out() on the fitted ColumnTransformer returns names prefixed with the step name, such as cat__city_Berlin or num__age. The prefix keeps names unique when two transformers produce similar columns. To remove the prefixes, build the transformer with verbose_feature_names_out=False. This raises an error if the resulting names would collide.
Sparse output deserves attention. OneHotEncoder returns a sparse matrix by default. ColumnTransformer keeps the combined result sparse only when its density is below sparse_threshold, which defaults to 0.3. Otherwise it returns a dense array. Most scikit-learn models accept either form. If you need a DataFrame for inspection, call set_output(transform="pandas") on the transformer.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
X = pd.DataFrame({
"city": ["Paris", "Berlin", "Paris", "Rome"],
"age": [25, 32, 47, 51],
})
preprocess = ColumnTransformer(
[
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
("num", StandardScaler(), ["age"]),
],
verbose_feature_names_out=False,
)
preprocess.set_output(transform="pandas")
print(preprocess.fit_transform(X))Choosing columns
Explicit name lists are the safest option. They fail loudly when a column is missing. You can also select by data type with make_column_selector.
from sklearn.compose import make_column_selector
selector = make_column_selector(dtype_include=object)Dtype selection is convenient, but it depends on how pandas stored the column. Text columns may be object, string or category depending on your pandas version and settings. Numeric codes that represent categories, such as a zip code stored as an integer, are never picked up as categorical. Check what the selector actually chose before trusting it.
What happens to the other columns
By default remainder="drop". Any column you did not mention is silently discarded. That is a common source of "my model ignores a feature" bugs. You have two alternatives:
remainder="passthrough"appends the untouched columns to the output.remainder=some_transformerapplies a transformer to everything not listed.
Choose deliberately. Passthrough on a text column will make the downstream model fail with a conversion error, which at least tells you something is wrong. Dropping fails silently.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: Found unknown categories` at predict time | Encoder left at `handle_unknown="error"` | Set `handle_unknown="ignore"`, or `"infrequent_if_exist"` if you group rare values |
| `ValueError: A given column is not a column of the dataframe` | Column names differ between fit and predict data | Pass DataFrames with the same column names. Do not rename columns after fitting |
| Model quality is suspiciously good in validation | Preprocessing was fitted before the split | Put every learned step inside the pipeline and split first |
| Fewer features than expected | `remainder="drop"` discarded unlisted columns | List every column, or set `remainder="passthrough"` |
| Error mentioning sparse data when using pandas output | Encoder still returns sparse output | Set `sparse_output=False` |
| Different feature order after reloading | Rebuilt the transformer with a changed column list | Persist and reload the fitted pipeline (for example with `joblib`) instead of rebuilding it |
Design decisions
Keep the encoder inside the pipeline even if the model is a tree ensemble that does not need scaling. The benefit is not the scaling. It is that one object holds all the learned state, so you can save it, version it and serve it.
If you tune hyperparameters, you can search over encoder settings as well as model settings. For example, GridSearchCV can try prep__cat__onehot__min_frequency values, using the double-underscore path from the step names. Each candidate is refitted on the training folds, so the choice is validated honestly.
If a column set is large and varied, build the ColumnTransformer from lists generated from a schema file. Do not rely on selector magic that changes when the data loader changes.
Exercise
You build a pipeline with a ColumnTransformer that lists ["city", "plan"] for one-hot encoding and ["age"] for scaling. Your DataFrame also has a numeric "income" column that you forgot to list. You call model.fit(Xtrain, ytrain) and it succeeds. Is "income" used by the model? What setting controls this, and how would you include it unchanged?
Show answer
No. With the default remainder="drop", unlisted columns are discarded without any warning, so the model never sees "income". Set remainder="passthrough" on the ColumnTransformer to append it unchanged, or add it to the numeric list so it is imputed and scaled. In both cases, check the output of getfeaturenames_out() to confirm the column is present.