Sub topic 12
Putting it in a ColumnTransformer and Pipeline
This chapter assumes you know how to use OneHotEncoder and StandardScaler on their own, what a train/test split is, and that you can read a pandas DataFrame. It shows how to combine them into one object that you can fit, evaluate and reuse.
Why a single object helps
Real datasets mix column types. A city column needs one-hot encoding, while an age column needs scaling. If you transform each column by hand, you must remember to fit every step on the training data only and to repeat each step on new data in the same order. Mistakes here are easy to make, and they are hard to notice.
Two scikit-learn tools remove that risk:
ColumnTransformerapplies a different transformer to each group of columns and joins the results into one feature matrix.Pipelinechains the preprocessing step and a model, sofitandpredictrun the whole sequence.
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
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))Each entry in the ColumnTransformer list is a tuple of a name, a transformer and the columns it handles. The name lets you find the step later. Here "cat" receives city and "num" receives age.
What happens during fit and predict
When you call model.fit(X, y), the pipeline first fits preprocess on X. The encoder learns the cities and the scaler learns the mean and standard deviation of age. The transformed matrix then goes to the classifier. When you call model.predict(new_X), the pipeline only transforms with what was already learned, then predicts.
This design also prevents leakage. If you pass the pipeline to cross_val_score or GridSearchCV, scikit-learn refits the whole preprocessing step inside each training fold. The validation fold never influences the learned categories or the scaling statistics.
Inspecting the result
You can look inside a fitted pipeline by step name:
names = model.named_steps["prep"].get_feature_names_out()
print(names)For the example above, this gives cat__city_Berlin, cat__city_Paris, cat__city_Rome and num__age. The prefix is the name you gave each transformer. This is useful when you check model coefficients.
Common errors
- Passing a string instead of a list.
"city"selects a one-dimensional Series, andOneHotEncoderexpects two dimensions. Use["city"]. - Forgetting
remainder. By default, columns not listed are dropped. Setremainder="passthrough"to keep them unchanged. - Transforming test data separately. Call
model.predict(X_test)instead of running the preprocessor yourself on test data with a new fit. - Misspelled column names. The error appears at fit time as a
KeyError, so check the names againstX.columns.
Exercise
Exercise
A pipeline has a ColumnTransformer with ("cat", OneHotEncoder(), ["city"]) and ("num", StandardScaler(), ["age"]). Your DataFrame also has an income column that you did not list. What happens to income by default, and how do you keep it unscaled?
Show answer
By default, ColumnTransformer uses remainder="drop", so income is removed from the output. Add remainder="passthrough" to the ColumnTransformer to keep income as it is.