# scikit-learn Pipeline and ColumnTransformer in Python

> How to use scikit-learn Pipeline and ColumnTransformer to preprocess numeric, categorical, and text columns, avoid data leakage, tune the whole pipeline with GridSearchCV, and add custom steps.

Source: https://www.pythoncharts.com/machine-learning/sklearn-pipeline-columntransformer-python/ | Published: 2026-11-26 | Author: Alex Scott | Category: Machine Learning | Tags: machine learning, scikit-learn, pipeline, columntransformer, preprocessing, data leakage, cross validation

A scikit-learn `Pipeline` chains preprocessing steps and a model so that one `fit()` call runs them all, and `ColumnTransformer` sends different columns to different steps. Cross-validating the pipeline fits every step on training folds only, which prevents data leakage.

## Quick Example

This example makes up 1,200 food delivery orders with missing values, numbers, and categories, builds a pipeline that predicts which orders arrive late, and compares it with a guess-the-majority baseline.

```python
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
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

rng = np.random.default_rng(66)
n = 1200
orders = pd.DataFrame({
    "distance_km": rng.gamma(3, 1.3, n).round(1),
    "items": rng.integers(1, 9, n),
    "prep_minutes": rng.normal(18, 6, n).clip(4).round(),
    "vehicle": rng.choice(["bike", "scooter", "car"], n, p=[0.45, 0.35, 0.2]),
    "weather": rng.choice(["clear", "rain", "snow"], n, p=[0.7, 0.24, 0.06]),
})
slow = orders.vehicle.map({"bike": 0.34, "scooter": 0.12, "car": 0.0})
bad = orders.weather.map({"clear": 0.0, "rain": 0.8, "snow": 2.0})
log_odds = (-5 + slow * orders.distance_km + 0.14 * orders.prep_minutes
            + 0.1 * orders["items"] + bad)
late = rng.binomial(1, 1 / (1 + np.exp(-log_odds)))
orders.loc[rng.random(n) < 0.08, "prep_minutes"] = np.nan
orders.loc[rng.random(n) < 0.05, "weather"] = np.nan

numeric = ["distance_km", "items", "prep_minutes"]
categorical = ["vehicle", "weather"]

preprocess = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer(strategy="median")),
                      ("scale", StandardScaler())]), numeric),
    ("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                      ("encode", OneHotEncoder(handle_unknown="ignore"))]),
     categorical),
])
model = Pipeline([("preprocess", preprocess),
                  ("classify", LogisticRegression())])

X_train, X_test, y_train, y_test = train_test_split(
    orders, late, test_size=0.25, stratify=late, random_state=66)

baseline = DummyClassifier(strategy="prior")
results = {name: cross_val_score(est, X_train, y_train, cv=5, scoring="roc_auc")
           for name, est in [("Baseline", baseline), ("Pipeline", model)]}
model.fit(X_train, y_train)
print({name: scores.mean().round(3) for name, scores in results.items()})
print("test accuracy:", round(model.score(X_test, y_test), 3))

fig, ax = plt.subplots(figsize=(8, 3.2), layout="constrained")
for row, (name, scores) in enumerate(results.items()):
    ax.scatter(scores, np.full(5, row), s=50, color="#0e7490", alpha=0.7,
               label="Each fold" if row == 0 else None)
    ax.plot([scores.mean()] * 2, [row - 0.25, row + 0.25], color="#be123c", lw=3,
            label="Mean" if row == 0 else None)
ax.set_yticks([0, 1], list(results))
ax.set(title="5-fold cross-validated ROC AUC", xlabel="ROC AUC",
       xlim=(0.4, 0.9), ylim=(-0.6, 1.6))
ax.legend(loc="center")
plt.show()
```

![Cross-validated ROC AUC by fold, with the pipeline between 0.79 and 0.84 and the baseline at 0.5](https://www.pythoncharts.com/machine-learning/sklearn-pipeline-columntransformer-python/images/pipeline-quick-example.png)

About 31% of orders are late. The pipeline averages an AUC of 0.81 across folds, against 0.5 for the baseline, which gives every order the same score. On the test set it is right 74% of the time, compared with 69% for always predicting "on time". Missing values are filled and text columns encoded inside `fit()`, using only the training rows.

## How a ColumnTransformer Routes Columns

Each entry in a `ColumnTransformer` is a `(name, transformer, columns)` tuple. The outputs are placed side by side. Columns you don't list are dropped unless you set `remainder="passthrough"`. `get_feature_names_out()` shows what comes out.

```python
fitted = model.named_steps["preprocess"]
print(fitted.get_feature_names_out())
print(fitted.transform(X_test.head(3)).shape)

# Statistics learned from the training data only
print(fitted.named_transformers_["num"].named_steps["impute"].statistics_)
```

Three numeric columns stay three columns, and the two categorical columns become six indicators. The last line shows the medians used to fill gaps, in the order of the `numeric` list.

In a Jupyter notebook, displaying `model` draws an interactive diagram of the steps. `set_output(transform="pandas")` makes `transform()` return a DataFrame with those names.

## Select Columns by Type with make_column_transformer

`make_pipeline` and `make_column_transformer` name the steps for you, and `make_column_selector` picks columns by dtype, so new columns are handled without editing a list.

```python
from sklearn.compose import make_column_selector, make_column_transformer
from sklearn.pipeline import make_pipeline

short = make_pipeline(
    make_column_transformer(
        (make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
         make_column_selector(dtype_include=np.number)),
        (make_pipeline(SimpleImputer(strategy="most_frequent"),
                       OneHotEncoder(handle_unknown="ignore")),
         make_column_selector(dtype_exclude=np.number)),
    ),
    LogisticRegression(),
)
print(cross_val_score(short, X_train, y_train, cv=5, scoring="roc_auc").mean().round(3))
print(list(short.named_steps))
```

`handle_unknown="ignore"` matters in production: a category that never appeared in training becomes all zeros instead of raising an error.

## Tune the Whole Pipeline with GridSearchCV

Reach into a pipeline by joining step names with double underscores. A search can change preprocessing settings, model settings, or swap the model.

```python
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV

grid = [
    {"classify": [LogisticRegression()],
     "classify__C": [0.01, 0.1, 1, 10],
     "preprocess__num__impute__strategy": ["mean", "median"]},
    {"classify": [RandomForestClassifier(random_state=66)],
     "classify__min_samples_leaf": [1, 10, 30]},
]
search = GridSearchCV(model, grid, cv=5, scoring="roc_auc", n_jobs=-1)
search.fit(X_train, y_train)

table = pd.DataFrame(search.cv_results_)
table["label"] = [
    f"Logistic, C={p['classify__C']}, {p['preprocess__num__impute__strategy']}"
    if "classify__C" in p
    else f"Forest, leaf={p['classify__min_samples_leaf']}"
    for p in table.params]
table = table.sort_values("mean_test_score")

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
colors = np.where(table.label.str.startswith("Forest"), "#65a30d", "#6366f1")
ax.errorbar(table.mean_test_score, table.label, xerr=table.std_test_score,
            fmt="none", ecolor="#cbd5e1", capsize=3)
ax.scatter(table.mean_test_score, table.label, color=colors, zorder=3, s=45)
ax.set(title="Grid search results (mean ± one standard deviation across folds)",
       xlabel="Cross-validated ROC AUC")
ax.title.set_fontsize(11)
plt.show()
```

![Grid search results ranked by cross-validated ROC AUC, with logistic regression and a random forest with leaf size 10 close together near 0.81](https://www.pythoncharts.com/machine-learning/sklearn-pipeline-columntransformer-python/images/pipeline-grid-search.png)

The best result is logistic regression with `C=1` at 0.812, but several settings are within 0.002 of it, far less than the spread between folds. The imputation strategy makes almost no difference here. A random forest with `min_samples_leaf=10` is about as good, and one with fully grown trees is worst. When scores are this close, take the simpler model. For larger searches, [Optuna](https://www.pythoncharts.com/machine-learning/optuna-hyperparameter-tuning-python/) works with pipelines too.

## Plot Coefficients with Their Feature Names

Index a pipeline to get its parts: `model[:-1]` is everything before the model, and `model[-1]` is the model.

```python
names = model[:-1].get_feature_names_out()
weights = pd.Series(model[-1].coef_[0], index=[n.split("__")[1] for n in names])
weights = weights.sort_values()

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
ax.barh(weights.index, weights,
        color=np.where(weights > 0, "#c2410c", "#0e7490"))
ax.axvline(0, color="#334155", lw=1)
ax.set(title="What raises or lowers the chance of a late order",
       xlabel="Logistic regression coefficient")
plt.show()
```

![Horizontal bar chart of pipeline coefficients, with snow, preparation time, bikes and distance raising the chance of a late order and clear weather lowering it](https://www.pythoncharts.com/machine-learning/sklearn-pipeline-columntransformer-python/images/pipeline-coefficients.png)

Snow, longer preparation times, and bikes raise the chance of a late order the most. Numeric coefficients are per standard deviation, because of the scaler. Every category got its own column, so a category's coefficient is relative to the others in its group: rain is negative only because snow is so much worse. Compare rain with clear weather (-0.24 against -0.95) and rain still raises the risk.

## Add a Custom Step with FunctionTransformer

Wrap a function in `FunctionTransformer` to create features inside the pipeline. `feature_names_out` names the new columns.

```python
from sklearn.preprocessing import FunctionTransformer

def bike_distance(frame):
    return (frame.distance_km * (frame.vehicle == "bike")).to_frame("bike_km")

def bike_names(transformer, input_names):
    return ["bike_km"]

extra = ColumnTransformer([
    ("bike", FunctionTransformer(bike_distance, feature_names_out=bike_names),
     ["distance_km", "vehicle"]),
])
columns = ColumnTransformer(preprocess.transformers + extra.transformers)
engineered = Pipeline([("preprocess", columns), ("classify", LogisticRegression())])
print(cross_val_score(engineered, X_train, y_train, cv=5,
                      scoring="roc_auc").mean().round(3))
```

The distance matters more on a bike, and this feature gives the linear model a way to use that. AUC rises from 0.812 to 0.823.

Both functions are defined with `def` because `pickle` can't save a lambda. To load a pipeline that uses them elsewhere, put them in a module that both programs import.

## Save and Load a Pipeline

Save the fitted pipeline with `joblib`, and the preprocessing travels with the model.

```python
import joblib

joblib.dump(model, "late_orders.joblib")
loaded = joblib.load("late_orders.joblib")
order = pd.DataFrame({"distance_km": [7.5], "items": [3], "prep_minutes": [np.nan],
                      "vehicle": ["bike"], "weather": ["hail"]})
print(loaded.predict_proba(order)[:, 1].round(3))
```

The loaded pipeline gives this order a 76% chance of being late. It fills in the missing preparation time and ignores `hail`, a weather value it never saw.

Only load files you trust, because loading a pickle can run code. Load them with the same scikit-learn version that saved them.

## Practical Tips

- Put every step that learns from data inside the pipeline, including imputation, scaling, encoding, and [feature selection](https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/).
- Pass DataFrames with the same column names at prediction time.
- `OneHotEncoder(min_frequency=10)` groups rare categories into one column.
- Tree models don't need scaling. `HistGradientBoostingClassifier` also handles missing values itself.
- Use [permutation importance](https://www.pythoncharts.com/machine-learning/feature-importance-python/) on the whole pipeline to rank the original columns.

## Similar Topics

- [Train/Test Split and Cross-Validation in Python](https://www.pythoncharts.com/machine-learning/train-test-split-cross-validation-python/)
- [Logistic Regression in Python: Fit, Interpret, and Plot](https://www.pythoncharts.com/machine-learning/logistic-regression-python/)
- [Partial Dependence and ICE Plots in Python](https://www.pythoncharts.com/machine-learning/partial-dependence-ice-plot-python/)
