Skip to main content

AI and machine learning · Intermediate · 22 min

Build a scikit-learn pipeline with ColumnTransformer

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · scikit-learn 1.9.1 · pandas 3.1.1 · skops 0.16.0

You will have one scikit-learn pipeline that imputes, scales and one-hot encodes a mixed customer table, trains a churn model, survives cross-validation and unseen categories, and is saved and reloaded with skops instead of pickle.

On this page

Real tables mix kinds of columns. A customer export has numbers with gaps, text categories with gaps, and categories next month that it did not have this month. Each kind needs different preparation before a model can use it, and the preparation has to be learned from training data only, then repeated exactly at prediction time.

scikit-learn solves this with two pieces. A ColumnTransformer sends each group of columns through its own steps and joins the results. A Pipeline chains that preparation with a model, so fit, predict, cross-validation and saving all treat the whole chain as one object. Nothing is fitted by hand, so nothing can drift between training and serving.

In this tutorial you build that pipeline for a subscription business that wants to know which customers are likely to cancel next month. The data is 3,000 generated customers across four cities, so the numbers are repeatable and no real person is involved. Everything runs on a laptop CPU in seconds.

Step 1 · Create the project and install the libraries

Make a throwaway folder and a virtual environment, then install pinned versions:

Bash
mkdir -p ~/churn-pipeline-demo
cd ~/churn-pipeline-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet scikit-learn==1.9.1 pandas==3.1.1 numpy==2.5.5 skops==0.16.0

skops is a small library from the scikit-learn ecosystem for saving models in a format that is checked when it loads. You use it in the last steps. The whole download is around 70 MB, most of it SciPy, NumPy and pandas. On prepaid mobile data, do it once on Wi-Fi; nothing later needs a connection.

Check it worked

Bash
python -c "import sklearn, pandas, skops; print(sklearn.__version__, pandas.__version__, skops.__version__)"

The output is 1.9.1 3.1.1 0.16.0.

Step 2 · Generate a customer table with gaps

Each row is one customer:

  • tenure_months: months since they signed up
  • monthly_spend: average monthly bill, some values missing
  • support_calls: calls to support in the last quarter
  • plan: prepaid, postpaid or business, some values missing
  • city: Lagos, Nairobi, Accra or Johannesburg
  • churned: 1 if they cancelled the next month, the thing to predict
Bash
cat > make_data.py <<'PY'
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
n = 3000

plans = rng.choice(["prepaid", "postpaid", "business"], size=n, p=[0.6, 0.3, 0.1])
cities = rng.choice(["Lagos", "Nairobi", "Accra", "Johannesburg"], size=n)
tenure = rng.integers(1, 61, size=n)
spend = rng.gamma(shape=2.0, scale=15.0, size=n).round(2)
calls = rng.poisson(1.5, size=n)

score = (
    -1.0
    - 0.04 * tenure
    + 0.6 * calls
    + 1.2 * (plans == "prepaid")
    - 0.02 * spend
    + 0.5 * (cities == "Lagos")
)
churned = (rng.random(n) < 1 / (1 + np.exp(-score))).astype(int)

df = pd.DataFrame({
    "tenure_months": tenure,
    "monthly_spend": spend,
    "support_calls": calls,
    "plan": plans,
    "city": cities,
    "churned": churned,
})

# Real exports have gaps: blank out some spend and plan values.
df.loc[rng.random(n) < 0.08, "monthly_spend"] = np.nan
df.loc[rng.random(n) < 0.05, "plan"] = None

df.to_csv("customers.csv", index=False)
print(df.shape)
print(df.isna().sum().to_dict())
print("churn rate:", round(df["churned"].mean(), 3))
PY
python make_data.py

The churn rule is hidden inside the generator: short tenure, many support calls, prepaid plans and Lagos all push risk up. A good pipeline should find that pattern without being told.

Check it worked

The output shows (3000, 6), then the missing counts: monthly_spend has 266 gaps, plan has 133 and every other column has 0. The churn rate is 0.301.

Step 3 · Describe the preparation with ColumnTransformer

Put the preparation in its own module so that every later script imports the same definition. Numbers get the median in place of a gap, then standard scaling. Categories get the most common value in place of a gap, then one column per category:

Bash
cat > features.py <<'PY'
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

NUMERIC = ["tenure_months", "monthly_spend", "support_calls"]
CATEGORICAL = ["plan", "city"]

numeric_steps = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale", StandardScaler()),
])

categorical_steps = Pipeline([
    ("impute", SimpleImputer(strategy="most_frequent")),
    ("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
])

preprocess = ColumnTransformer([
    ("num", numeric_steps, NUMERIC),
    ("cat", categorical_steps, CATEGORICAL),
])
PY

Three choices here matter later:

  • handle_unknown="ignore" tells the encoder what to do with a city it never saw in training: give it zeros in every city column. The default, "error", raises a ValueError at prediction time, which takes a live service down the first time a new branch opens.
  • sparse_output=False returns an ordinary dense array. With five categories that costs nothing, and pandas output (later in this tutorial) needs it.
  • Columns you do not list are dropped. That is the default remainder="drop", and it keeps the target or an ID column from sneaking in.

Nothing has been learned yet: preprocess is only a recipe. Now fit it once to see what it produces:

Bash
cat > inspect_features.py <<'PY'
import pandas as pd

from features import preprocess

df = pd.read_csv("customers.csv")
X = df.drop(columns="churned")

matrix = preprocess.fit_transform(X)
print(matrix.shape)
for name in preprocess.get_feature_names_out():
    print(name)
PY
python inspect_features.py

get_feature_names_out walks every branch and reports the name of each output column, prefixed with the branch name you gave it.

Check it worked

The first line is (3000, 10). Below it are ten names: num__tenure_months, num__monthly_spend, num__support_calls, then cat__plan_business, cat__plan_postpaid, cat__plan_prepaid and the four cat__city_... columns. Five input columns became ten model columns, and there are no gaps left.

Step 4 · Join the preparation and a model in one Pipeline

Add a logistic regression after the preparation and train on three quarters of the data:

Bash
cat > train.py <<'PY'
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline

from features import preprocess

df = pd.read_csv("customers.csv")
X = df.drop(columns="churned")
y = df["churned"]

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=0, stratify=y
)

model = Pipeline([
    ("prep", preprocess),
    ("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)

print("test accuracy:", round(model.score(X_test, y_test), 3))
print("medians learned:", model.named_steps["prep"].named_transformers_["num"]
      .named_steps["impute"].statistics_)
PY
python train.py

model.fit fits the imputers, the scaler and the encoder on X_train only, transforms it, then fits the classifier. model.score on X_test reuses what was learned from training. The test rows never influence a median or a scaling factor, which is the whole point: if you had imputed and scaled the full table before splitting, the test score would be quietly flattered by information it should not have.

The last line reads the fitted values back out. named_steps and named_transformers_ let you reach any part of the chain by the name you gave it.

Check it worked

The output is test accuracy: 0.76 and the three learned medians, [31. 25.14 1.], for tenure, spend and support calls. The medians come from the 2,250 training rows, not all 3,000.

Step 5 · Cross-validate the whole pipeline

A single split gives one number that depends on which rows landed in the test set. Cross-validation repeats the split. Pass it the pipeline, not a preprocessed matrix, so that the preparation is refitted inside every fold:

Bash
cat > cv.py <<'PY'
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import Pipeline

from features import preprocess

df = pd.read_csv("customers.csv")
X = df.drop(columns="churned")
y = df["churned"]

model = Pipeline([
    ("prep", preprocess),
    ("clf", LogisticRegression(max_iter=1000)),
])

folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=folds, scoring="roc_auc")
print("ROC AUC per fold:", scores.round(3))
print("mean:", round(scores.mean(), 3))
PY
python cv.py

cross_val_score clones the pipeline for each of the five folds, fits the clone on four fifths of the rows and scores it on the fifth. ROC AUC measures how well the model ranks churners above non-churners: 0.5 is guessing, 1.0 is perfect.

Check it worked

You see five scores and their mean, something like [0.794 0.785 0.792 0.739 0.787] and mean: 0.779. The spread between folds, here about five points, is a useful reminder of how much a single split can move.

Step 6 · Get pandas output and read the model by feature name

A NumPy array has no column names, so debugging a transformed row means counting positions. set_output(transform="pandas") makes every transformer in the pipeline return a DataFrame with the names from get_feature_names_out:

Bash
cat > coefficients.py <<'PY'
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

from features import preprocess

df = pd.read_csv("customers.csv")
X = df.drop(columns="churned")
y = df["churned"]

model = Pipeline([
    ("prep", preprocess),
    ("clf", LogisticRegression(max_iter=1000)),
])
model.set_output(transform="pandas")
model.fit(X, y)

transformed = model.named_steps["prep"].transform(X.head(3))
print(type(transformed).__name__)
print(transformed.round(2).to_string())

weights = pd.Series(
    model.named_steps["clf"].coef_[0],
    index=model.named_steps["prep"].get_feature_names_out(),
)
print(weights.sort_values().round(2).to_string())
PY
python coefficients.py

This only works because the encoder returns dense output. With sparse_output=True, set_output raises an error, since pandas cannot hold a sparse matrix as an ordinary DataFrame.

Check it worked

The script prints DataFrame, then the first three customers as ten named columns of scaled numbers and zeros and ones. Below that is each feature's weight, smallest first. cat__plan_prepaid (about 0.95) and num__support_calls (about 0.74) are the strongest pushes towards churn, and num__tenure_months (about -0.61) the strongest push away, which matches the rule hidden in the generator. Because the numeric columns are scaled, their weights are comparable with each other.

Step 7 · Save the fitted pipeline with skops

The fitted pipeline holds everything needed to predict: the medians, the scaling, the category lists and the model weights. Save it as one file. Python's pickle, and joblib, which uses it, can run arbitrary code while loading a file, so a model file from someone else, or one that could have been swapped on a shared drive or bucket, is a security risk. The Python documentation says never to unpickle data you do not trust. skops stores the object in a format it inspects before loading, and refuses types you have not approved.

Bash
cat > save.py <<'PY'
import pandas as pd
import skops.io as sio
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline

from features import preprocess

df = pd.read_csv("customers.csv")
X = df.drop(columns="churned")
y = df["churned"]

model = Pipeline([
    ("prep", preprocess),
    ("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X, y)

sio.dump(model, "churn-model.skops")
print("saved churn-model.skops")
PY
python save.py

This time the pipeline is fitted on all 3,000 rows. You already measured it with cross-validation; the final model should learn from everything you have.

Check it worked

Bash
ls -l churn-model.skops

The file exists and is under 1 MB.

Step 8 · Load the model and predict for new customers

The prediction script lists the types in the file that skops does not trust by default, stops if any of them is not on the list you reviewed, and only then loads. Then it scores three new customers, one with a missing spend, one with a missing plan, and one in Kumasi, a city the model never saw:

Bash
cat > predict.py <<'PY'
import numpy as np
import pandas as pd
import skops.io as sio

PATH = "churn-model.skops"
REVIEWED = {"numpy.dtype"}

unknown = sio.get_untrusted_types(file=PATH)
print("types not trusted by default:", unknown)
surprises = set(unknown) - REVIEWED
if surprises:
    raise SystemExit(f"Refusing to load {PATH}: unreviewed types {sorted(surprises)}")

model = sio.load(PATH, trusted=sorted(REVIEWED))

new_customers = pd.DataFrame({
    "tenure_months": [3, 48, 12],
    "monthly_spend": [12.5, np.nan, 40.0],
    "support_calls": [4, 0, 1],
    "plan": ["prepaid", "postpaid", None],
    "city": ["Lagos", "Nairobi", "Kumasi"],
})

risk = model.predict_proba(new_customers)[:, 1]
for city, p in zip(new_customers["city"], risk):
    print(f"{city}: {p:.2f}")
PY
python predict.py

numpy.dtype is a plain NumPy data type description, which is why it is the one entry on the reviewed list. Do not pass whatever get_untrusted_types returns straight to trusted=: that approves anything a tampered file contains. When you upgrade scikit-learn or skops and the list changes, read the new names before you add them.

Load the file with the same scikit-learn version that saved it. A different version can load with a warning and behave differently, so pin versions in the service that loads the model, as you did here.

Check it worked

The output is:

Text
types not trusted by default: ['numpy.dtype']
Lagos: 0.93
Nairobi: 0.04
Kumasi: 0.39

The missing spend and plan were filled with the training median and most common plan, and Kumasi got zeros in every city column, so its risk rests on its other features. A new long-tenure postpaid customer is a low risk; a three-month prepaid customer with four support calls is a high one. If you see Refusing to load, the file holds a type you have not reviewed: find out where the file came from before going further.

Step 9 · Clean up

Leave the virtual environment and remove the demo folder, including the saved model:

Bash
deactivate
cd ~
rm -rf ~/churn-pipeline-demo

Check it worked

ls ~/churn-pipeline-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.