Stop 06 · Data Preparation & Feature EngineeringTopics · 10/10

scikit-learn Pipelines & ColumnTransformer

Part of the Machine Learning Roadmap

In short

Real tables mix numbers, categories and missing values, and each needs different preparation. A Pipeline with a ColumnTransformer packs all of it, plus the model, into one object you can fit, cross-validate and ship.

A Pipeline chains preprocessing and a model into one object, and ColumnTransformer applies different steps to numeric and categorical columns. Together they prevent leakage, keep code tidy and let you save the whole thing as one file.

The jaadu oversees a kitchen conveyor belt where separate stations add roti, dal and rice to steel thalis rolling past.

Think of it like this

The thali assembly line

In a big mess kitchen, rotis go to one station, dal to another, rice to a third, and then everything meets on one thali. ColumnTransformer is that set of stations, each column type getting its own treatment. The Pipeline is the conveyor belt that always runs the stations in the same order, for practice plates and real customers alike.

Watch it happen

fit() on a mixed table

Raw DataFrame
Split by column
Impute + scale
Impute + one-hot
Model

1/5A loan table: income, age, loan amount, city, employment type. Some values are missing.

The big ideas

What you need to know

Pipeline chains steps

Each step's output feeds the next. Calling fit runs fit_transform on every step and fit on the model at the end.

ColumnTransformer routes columns

Give it (name, transformer, columns) triples. Each group of columns gets its own preprocessing.

Leakage-proof by design

Inside cross_val_score or GridSearchCV, preprocessing is refit on each training fold automatically.

One file to deploy

joblib.dump saves preprocessing and model together, so production applies exactly the same steps.

See it in code

Walk through the code

python
1import joblib2import pandas as pd3from sklearn.compose import ColumnTransformer4from sklearn.ensemble import RandomForestClassifier5from sklearn.impute import SimpleImputer6from sklearn.model_selection import cross_val_score7from sklearn.pipeline import Pipeline8from sklearn.preprocessing import OneHotEncoder, StandardScaler9 10df = pd.read_csv("loans.csv")11X, y = df.drop(columns="defaulted"), df["defaulted"]12 13num_cols = ["income", "age", "loan_amount"]14cat_cols = ["city", "employment_type"]15 16numeric = Pipeline([("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())])17categorical = Pipeline([18    ("impute", SimpleImputer(strategy="constant", fill_value="missing")),19    ("onehot", OneHotEncoder(handle_unknown="ignore")),20])21 22prep = ColumnTransformer([("num", numeric, num_cols), ("cat", categorical, cat_cols)])23model = Pipeline([("prep", prep), ("clf", RandomForestClassifier(random_state=0))])24 25print(cross_val_score(model, X, y, cv=5, scoring="roc_auc").mean())26model.fit(X, y)27joblib.dump(model, "loan_model.joblib")

1/5List which columns are numeric and which are categorical.

Mixed-type preprocessing and a model in one object, cross-validated and saved.

Save yourself the pain

Common mistakes

Oops

Preprocessing with pandas, then saving only the model.

Do this instead

Production then has to repeat every step by hand and often gets one wrong. Save the full Pipeline instead.

Oops

Leaving OneHotEncoder with the default handle_unknown.

Do this instead

Set handle_unknown='ignore' so a category never seen in training doesn't crash prediction.

Your mission

Pipeline a messy dataset

~35 min

Quick check

What is the main reason to put StandardScaler inside a Pipeline before cross-validation?

Go deeper

  1. 1Build a ColumnTransformer with an imputer and scaler for numbers and a one-hot encoder for categories.
  2. 2Put it in a Pipeline with a model and run cross_val_score on the whole pipeline.
  3. 3Save the fitted pipeline with joblib and use it to predict on raw new rows.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge