Pipelines and ColumnTransformer

Python · Machine Learning (Scikit-Learn)

Theory

A Pipeline chains preprocessing steps and a final model into one estimator: Pipeline([('scale', StandardScaler()), ('model', LogisticRegression())]). Calling fit runs fit_transform on each step in order and fits the model; calling predict runs transform on each step and predicts. make_pipeline does the same and names the steps automatically.

Real tables need different treatment per column, which is what ColumnTransformer does: numeric columns go through an imputer and scaler, categorical ones through an imputer and OneHotEncoder, and the outputs are joined side by side. Put the ColumnTransformer inside a Pipeline with the model and the whole thing fits on a raw DataFrame. Because every step is fitted only on the data passed to fit, cross-validation and GridSearchCV with a pipeline cannot leak test information. Step parameters are addressed as step__param, for example model__C.

Why we use it

Without a pipeline it is easy to fit a scaler on all the data, forget a step at prediction time or apply steps in the wrong order. A pipeline packages the full recipe so training, evaluation and deployment use exactly the same transformations.

When to use it

Use a pipeline whenever there is any preprocessing before the model, and always when cross-validating or tuning. Use ColumnTransformer when numeric and categorical columns need different steps. Save the whole pipeline, not just the model.

How it works

  1. Raw DataFrame: numeric + categorical columns
  2. ColumnTransformer splits columns by type
  3. Numeric: impute median, then scale
  4. Categorical: impute most frequent, then one-hot
  5. Outputs joined side by side into one matrix
  6. Final step: the model fits / predicts
  7. One estimator: pipe.fit(X, y), pipe.predict(X_new)

Syntax

from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.compose import ColumnTransformer
pre = ColumnTransformer([('num', num_pipe, num_cols), ('cat', cat_pipe, cat_cols)])
clf = Pipeline([('prep', pre), ('model', LogisticRegression())])
clf.fit(X_train, y_train)

Example

pre = ColumnTransformer([('num', StandardScaler(), ['income']),
                         ('cat', OneHotEncoder(handle_unknown='ignore'), ['city'])])
clf = make_pipeline(pre, LogisticRegression())
clf.fit(X_train, y_train)

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic