scikit-learn Pipeline and ColumnTransformer Tutorial: Preprocess, Tune, Save and Predict (2026)

Data Sciences Dec 03, 2026

Watch on YouTube

Almost every tabular machine learning project needs the same chores before a model can learn anything: fill missing values, scale numbers, turn text categories into numbers, and then do exactly the same steps on new data at prediction time. If you do these steps by hand on the full DataFrame, you leak information from the test set into training and you end up with a model that only works inside your notebook. scikit-learn solves this with two classes: Pipeline chains steps together, and ColumnTransformer applies different preprocessing to different columns. In this tutorial we build a customer churn model end to end with scikit-learn 1.9.1 (the current stable release), tune it with GridSearchCV, save it with joblib, predict on raw rows with missing values and unseen categories, and finally try the headline feature of the scikit-learn 1.10 release candidate published on 1 December 2026: random forests that read pandas category columns directly. Every output block below is the real output of the script above it.

Why use a Pipeline?

  • No data leakage: imputers and scalers learn their medians and means only from the training folds, even inside cross-validation.
  • One object to ship: preprocessing and model are saved together, so production code calls predict() on raw data.
  • Tunable end to end: grid search can tune preprocessing options (like the imputation strategy) and even swap the model.
  • Readable: each step has a name, and get_feature_names_out() tells you what the model actually sees.

Setup

uv venv -p 3.14 && source .venv/bin/activate
uv pip install "scikit-learn==1.9.1" pandas joblib
python step1_data.py

scikit-learn 1.9 needs Python 3.11 or newer; the 1.10 release candidate requires Python 3.12+. If you still use pandas 2, everything here works the same, but read our pandas 3 migration guide to see why text columns now load with the new str dtype.

Step 1: A realistic dataset with missing values

To keep the tutorial reproducible offline, we generate a churn table with a fixed random seed: three numeric columns, three text categories and a 0/1 target. We also blank out some values on purpose, because real data always has holes.

# Step 1: build a realistic customer-churn table with numbers, text categories and missing values
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n = 3000
contract = rng.choice(["month-to-month", "one-year", "two-year"], n, p=[0.55, 0.25, 0.20])
payment = rng.choice(["card", "bank-transfer", "e-check", "cash"], n)
internet = rng.choice(["fiber", "dsl", "none"], n, p=[0.45, 0.40, 0.15])
tenure = rng.integers(1, 73, n)
monthly = np.round(rng.normal(70, 25, n).clip(18, 140), 2)
support_calls = rng.poisson(1.5, n)

# churn risk: short tenure, monthly contracts, e-check, fiber and many support calls
logit = (-1.2 - 0.045 * tenure + 1.6 * (contract == "month-to-month") - 0.9 * (contract == "two-year")
         + 0.7 * (payment == "e-check") + 0.5 * (internet == "fiber") + 0.35 * support_calls
         + 0.012 * (monthly - 70))
churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)

df = pd.DataFrame({"tenure": tenure, "monthly_charges": monthly, "support_calls": support_calls,
                   "contract": contract, "payment_method": payment, "internet": internet, "churn": churn})
df.loc[rng.random(n) < 0.06, "monthly_charges"] = np.nan    # 6% missing numbers
df.loc[rng.random(n) < 0.04, "payment_method"] = np.nan     # 4% missing categories
df.to_csv("churn.csv", index=False)

print(df.head(5).to_string())
print("shape:", df.shape, "| churn rate:", round(df["churn"].mean(), 3))
print("missing:", df.isna().sum()[lambda s: s > 0].to_dict())
   tenure  monthly_charges  support_calls        contract payment_method internet  churn
0       6            30.85              0        one-year        e-check    fiber      0
1      37           108.00              1  month-to-month           cash      dsl      1
2      42            95.32              4        two-year        e-check      dsl      0
3      53            78.76              3        one-year        e-check      dsl      0
4      42              NaN              4  month-to-month  bank-transfer    fiber      1
shape: (3000, 7) | churn rate: 0.291
missing: {'monthly_charges': 197, 'payment_method': 111}

We have 3,000 customers, a churn rate of 0.291, 197 missing monthly charges and 111 missing payment methods. A plain LogisticRegression would crash on the NaN values and on the text columns, so we need preprocessing.

Step 2: Build the Pipeline with ColumnTransformer

Numbers get a median SimpleImputer followed by StandardScaler. Categories get a most-frequent imputer followed by OneHotEncoder(handle_unknown="ignore"). make_column_selector picks columns by dtype, so the code keeps working when you add a new column. The ColumnTransformer and the model are then chained in one Pipeline.

# Step 2: one Pipeline = preprocessing (ColumnTransformer) + model, no data leakage
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv("churn.csv")
X, y = df.drop(columns="churn"), df["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)

numeric = Pipeline([("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())])
categorical = Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                        ("onehot", OneHotEncoder(handle_unknown="ignore"))])
preprocess = ColumnTransformer([
    ("num", numeric, make_column_selector(dtype_include="number")),
    ("cat", categorical, make_column_selector(dtype_include=object)),
])
clf = Pipeline([("prep", preprocess), ("model", LogisticRegression(max_iter=1000))])

cv = cross_val_score(clf, X_train, y_train, cv=5, scoring="roc_auc")
print("5-fold CV ROC AUC:", cv.round(3), "mean", round(cv.mean(), 3))
clf.fit(X_train, y_train)
proba = clf.predict_proba(X_test)[:, 1]
print("test ROC AUC:", round(roc_auc_score(y_test, proba), 3))
print(classification_report(y_test, clf.predict(X_test), digits=3))
names = clf.named_steps["prep"].get_feature_names_out()
print(len(names), "features after preprocessing:", list(names[:5]), "...")
5-fold CV ROC AUC: [0.823 0.812 0.795 0.843 0.848] mean 0.824
test ROC AUC: 0.816
              precision    recall  f1-score   support

           0      0.826     0.895     0.859       532
           1      0.678     0.541     0.602       218

    accuracy                          0.792       750
   macro avg      0.752     0.718     0.731       750
weighted avg      0.783     0.792     0.784       750

13 features after preprocessing: ['num__tenure', 'num__monthly_charges', 'num__support_calls', 'cat__contract_month-to-month', 'cat__contract_one-year'] ...

Because the imputers and scaler live inside the pipeline, cross_val_score refits them on each training fold, so the 5-fold mean ROC AUC of 0.824 is an honest estimate. On the untouched test set the model reaches a ROC AUC of 0.816 and an accuracy of 0.792. The six raw columns became 13 model features: the three scaled numbers plus one column per category value, and get_feature_names_out() shows names such as cat__contract_month-to-month, prefixed with the name of the transformer that created them.

Step 3: Tune preprocessing and model together with GridSearchCV

Parameters of nested steps are addressed with double underscores: prep__num__impute__strategy means "the strategy of the impute step inside the num transformer of the prep step". You can even put estimators in the grid under the model key to compare completely different models with the same preprocessing.

# Step 3: tune preprocessing AND swap models inside one GridSearchCV
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv("churn.csv")
X, y = df.drop(columns="churn"), df["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
preprocess = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer()), ("scale", StandardScaler())]),
     make_column_selector(dtype_include="number")),
    ("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                      ("onehot", OneHotEncoder(handle_unknown="ignore"))]),
     make_column_selector(dtype_include=object)),
])
pipe = Pipeline([("prep", preprocess), ("model", LogisticRegression(max_iter=1000))])
grid = [
    {"prep__num__impute__strategy": ["mean", "median"],
     "model": [LogisticRegression(max_iter=1000)], "model__C": [0.1, 1.0, 10.0]},
    {"prep__num__impute__strategy": ["median"],
     "model": [HistGradientBoostingClassifier(random_state=0)],
     "model__learning_rate": [0.05, 0.1], "model__max_depth": [3, None]},
]
search = GridSearchCV(pipe, grid, cv=5, scoring="roc_auc", n_jobs=-1)
search.fit(X_train, y_train)
res = pd.DataFrame(search.cv_results_)
res["model"] = res["param_model"].map(lambda m: type(m).__name__)
best_each = res.sort_values("rank_test_score").groupby("model", sort=False).head(1)
print(best_each[["rank_test_score", "model", "mean_test_score", "mean_fit_time"]].round(4).to_string(index=False))
print("candidates tried:", len(res), "| best:", {k: (type(v).__name__ if k == "model" else v)
                                                for k, v in search.best_params_.items()})
print("best CV ROC AUC:", round(search.best_score_, 3),
      "| test ROC AUC:", round(roc_auc_score(y_test, search.predict_proba(X_test)[:, 1]), 3))
 rank_test_score                          model  mean_test_score  mean_fit_time
               1             LogisticRegression           0.8243         0.0193
               7 HistGradientBoostingClassifier           0.8185         0.0431
candidates tried: 10 | best: {'model': 'LogisticRegression', 'model__C': 0.1, 'prep__num__impute__strategy': 'median'}
best CV ROC AUC: 0.824 | test ROC AUC: 0.814

GridSearchCV evaluated 10 candidate pipelines with 5-fold cross-validation, using all CPU cores via n_jobs=-1. The best logistic regression (CV ROC AUC 0.8243) beat the best HistGradientBoostingClassifier (0.8185) on this data and was also faster to fit. That is a useful reminder: a gradient boosting model is not automatically better, especially when the signal is mostly linear. Always compare against a simple baseline. The tuned pipeline scored 0.814 ROC AUC on the test set.

Step 4: Save the whole pipeline and predict on raw data

Because preprocessing is part of the model, you save one file. The loaded pipeline accepts raw rows, including a missing number and a payment method it never saw in training ("crypto").

# Step 4: save the whole pipeline once, load it anywhere, predict on raw rows
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = pd.read_csv("churn.csv")
X, y = df.drop(columns="churn"), df["churn"]
pipe = Pipeline([
    ("prep", ColumnTransformer([
        ("num", Pipeline([("impute", SimpleImputer(strategy="median")), ("scale", StandardScaler())]),
         make_column_selector(dtype_include="number")),
        ("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                          ("onehot", OneHotEncoder(handle_unknown="ignore"))]),
         make_column_selector(dtype_include=object)),
    ])),
    ("model", LogisticRegression(C=1.0, max_iter=1000)),
]).fit(X, y)
joblib.dump(pipe, "churn_pipeline.joblib")

model = joblib.load("churn_pipeline.joblib")
new = pd.DataFrame([
    {"tenure": 2, "monthly_charges": 95.0, "support_calls": 4, "contract": "month-to-month",
     "payment_method": "e-check", "internet": "fiber"},
    {"tenure": 60, "monthly_charges": None, "support_calls": 0, "contract": "two-year",
     "payment_method": "crypto", "internet": "dsl"},          # missing value + unseen category
])
for row, p in zip(new.to_dict("records"), model.predict_proba(new)[:, 1]):
    print(f"tenure={row['tenure']:>2} contract={row['contract']:<15} payment={row['payment_method']:<8} -> churn risk {p:.1%}")
coefs = pd.Series(model[-1].coef_[0], index=model[0].get_feature_names_out()).sort_values()
print("strongest churn drivers:", coefs.tail(3).round(2).to_dict())
print("strongest loyalty drivers:", coefs.head(2).round(2).to_dict())
tenure= 2 contract=month-to-month  payment=e-check  -> churn risk 96.1%
tenure=60 contract=two-year        payment=crypto   -> churn risk 0.8%
strongest churn drivers: {'num__support_calls': 0.48, 'cat__payment_method_e-check': 0.54, 'cat__contract_month-to-month': 1.44}
strongest loyalty drivers: {'cat__contract_two-year': -1.21, 'num__tenure': -0.94}

The new month-to-month, e-check, fiber customer with 2 months of tenure got a churn risk of 96.1%, while the loyal two-year customer got 0.8%. The missing monthly_charges value was filled with the training median, and the unknown category was encoded as all zeros instead of raising an error, thanks to handle_unknown="ignore". The coefficients, matched with the feature names, show that a month-to-month contract is the strongest churn driver and a two-year contract and long tenure keep customers. Only load joblib or pickle files you created yourself, because unpickling can run code. For versioned storage of the same file, see our MLflow model registry guide, and to serve it over HTTP, see how to deploy a model as a FastAPI service.

Step 5: Native categorical features in random forests (scikit-learn 1.10 RC)

scikit-learn 1.10.0rc1 adds a categorical_features parameter to RandomForestClassifier, RandomForestRegressor, ExtraTreesClassifier and ExtraTreesRegressor. With "from_dtype", columns with the pandas category dtype are split natively, without one-hot encoding. We installed the release candidate in a separate virtual environment with uv pip install --prerelease=allow "scikit-learn==1.10.0rc1" and compared both approaches on the same rows.

# Step 5 (scikit-learn 1.10.0rc1): random forests read pandas category dtype directly
import time
import pandas as pd
import sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score

df = pd.read_csv("churn.csv").dropna()
y = df.pop("churn")
cats = ["contract", "payment_method", "internet"]
native = df.astype({c: "category" for c in cats})
onehot = pd.get_dummies(df, columns=cats, dtype=float)

for name, X, kw in [("one-hot + RandomForest", onehot, {}),
                    ("native categorical_features='from_dtype'", native, {"categorical_features": "from_dtype"})]:
    rf = RandomForestClassifier(n_estimators=200, min_samples_leaf=10, random_state=0, n_jobs=-1, **kw)
    t = time.perf_counter()
    auc = cross_val_score(rf, X, y, cv=5, scoring="roc_auc").mean()
    print(f"{name:<42} columns={X.shape[1]:>2}  CV ROC AUC={auc:.3f}  time={time.perf_counter() - t:.1f}s")
print("scikit-learn", sklearn.__version__)
one-hot + RandomForest                     columns=13  CV ROC AUC=0.811  time=1.5s
native categorical_features='from_dtype'   columns= 6  CV ROC AUC=0.811  time=1.6s
scikit-learn 1.10.0rc1

The native version needs only 6 columns instead of 13 and no encoder step, and it scored the same CV ROC AUC (0.811 versus 0.811). With many high-cardinality columns, the saving in memory and preprocessing code is much larger. Keep in mind the limits from the changelog: random forests support binary classification and single-output regression with up to 256 categories per feature, warm_start does not work with categorical features, and the default stays None until "from_dtype" becomes the default in 1.13. The release candidate also printed a harmless UserWarning about feature names during scoring; that is the kind of rough edge to expect from an RC, so test it but keep production on 1.9.1 until 1.10.0 final is out.

Best practices for scikit-learn pipelines in 2026

  • Split the data first, then fit the pipeline only on the training part. Never call fit_transform on the full dataset.
  • Select columns with make_column_selector or explicit lists, and use remainder="drop" (the default) so unexpected columns are ignored.
  • Use OneHotEncoder(handle_unknown="ignore") or "infrequent_if_exist" so new category values do not crash production.
  • Call set_output(transform="pandas") on the preprocessor when you want to inspect transformed data as a DataFrame with readable column names.
  • Pin the scikit-learn version you trained with; joblib files are not guaranteed to load in other versions.
  • Large data? Load and clean it with Polars or pandas first (see Polars vs pandas in 2026), then pass the final table to the pipeline.

Common errors and fixes

  • ValueError: Input X contains NaN: add a SimpleImputer step before the model, or use a model that supports missing values such as HistGradientBoostingClassifier.
  • ValueError: could not convert string to float: a text column reached the model. Check that the ColumnTransformer selects all object or str columns.
  • ValueError: Found unknown categories: set handle_unknown="ignore" on the OneHotEncoder.
  • ValueError: Invalid parameter for estimator Pipeline: a grid key is misspelled. Print pipe.get_params().keys() to see valid names like prep__num__impute__strategy.
  • InconsistentVersionWarning when loading a model: the file was saved with another scikit-learn version. Retrain or install the same version.

Conclusion

A scikit-learn Pipeline with a ColumnTransformer turns scattered preprocessing code into one tested, tunable and saveable object. In our run it delivered a leak-free 0.824 CV ROC AUC, let GridSearchCV compare 10 pipelines including two model families, and produced a single joblib file that predicted on raw rows with missing values and unseen categories. The upcoming scikit-learn 1.10 goes further by letting random forests use pandas categories directly. Start every tabular project with a pipeline and you will avoid the most common machine learning bugs before they happen.

FAQ

What is the difference between Pipeline and ColumnTransformer? A Pipeline runs steps one after another on all columns. A ColumnTransformer runs different transformers side by side on different column groups and concatenates the results. You usually put a ColumnTransformer as the first step of a Pipeline.

How do I tune a parameter inside a pipeline? Use the step names joined by double underscores, for example model__C or prep__num__impute__strategy, as keys in the GridSearchCV parameter grid.

Should I use make_pipeline or Pipeline? make_pipeline names the steps automatically from the class names, which is shorter. Pipeline with explicit names gives shorter and clearer grid keys, so it is better when you tune.

How do I save a scikit-learn pipeline? Use joblib.dump(pipe, "model.joblib") and joblib.load(). For files from untrusted sources, consider the skops format, which does not execute arbitrary code on load.

What is new in scikit-learn in 2026? Version 1.9 (June 2026) added experimental callbacks such as ProgressBar and the metric_at_thresholds function. The 1.10 release candidate (December 2026) adds native categorical features to random forests and extra trees and makes histogram gradient boosting faster.

Tested versions: Python 3.14.10 (CPython), scikit-learn 1.9.1, pandas 3.1.2, numpy 2.5.5, joblib 1.6.0 on Linux x86_64 (8 CPU cores); Step 5 uses scikit-learn 1.10.0rc1.

Share:
Last updated: December 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices