Skip to content
Visual explainer 3h 30m to learn 5 steps

Data preprocessing with scikit-learn pipelines

Build a ColumnTransformer pipeline that imputes, encodes and scales features while fitting only on the training split.

By Invicly Tech, , in AI and Machine Learning with Python. About 10 minutes to read.

Topic 7 of 34

In short

Real data has gaps, text categories and columns on wildly different scales, and most models need clean numbers. scikit-learn's ColumnTransformer applies the right steps to each column type, such as imputing, encoding and scaling, and a Pipeline joins those steps to the model. Fitting the whole pipeline on the training split only keeps test data truly unseen.

Think of it like this: A pipeline is a recipe followed in the same order every time, so tonight's dish matches the one you tasted when you wrote it.

Explained simply

Most models only understand numbers, with no gaps. Real data has empty cells, text categories like "basic" or "premium", and columns on very different scales, such as age in years and income in thousands. Preprocessing turns that raw table into clean numbers the model can use.

Missing values are usually filled in, which is called imputation. A common choice is the median of the column. Text categories become numbers, often with one-hot encoding: one 0/1 column per category. Scaling puts numeric columns on similar ranges so no column dominates just because its numbers are bigger.

Every one of these steps learns something from data: the median, the list of categories, the mean and spread. That learning must use the training data only. If the test data helps decide the median, the test is no longer a fair stand-in for the future.

scikit-learn makes this safe with a Pipeline. You describe the steps once, call fit on the training data, and the same fitted steps are applied to any new data. The same pipeline object can later be saved and used in production.

Press Play on a diagram to walk through it one step at a time.

MapA ColumnTransformer for mixed data
ColumnTransformer
  • Numeric columns
    • SimpleImputer(strategy="median")
    • StandardScaler()
  • Categorical columns
    • SimpleImputer(strategy="most_frequent")
    • OneHotEncoder(handle_unknown="ignore")
  • Skewed amounts
    • Clip or log transform
    • RobustScaler()
  • Everything else
    • remainder="drop" by default
FlowPreprocessing workflow before any model
  1. 1
    Profile

    Types, missing share, category counts, ranges.

  2. 2
    Fix errors at source

    Impossible values, wrong units.

  3. 3
    Split

    Train and test before fitting anything.

  4. 4
    Build ColumnTransformer

    One branch per column type.

  5. 5
    Fit pipeline on train

    Then score on test once.

In depth

Missing values: impute, flag or drop

First ask why values are missing. Missing completely at random, such as a sensor glitch, is easy to fill. Missing for a reason, such as income left blank by high earners, carries information, so keep it as a feature. SimpleImputer(strategy="median") fills numeric gaps robustly; strategy="most_frequent" or strategy="constant" suits categories. Setting add_indicator=True adds a 0/1 column marking which values were filled, so the model can learn from missingness itself.

Dropping rows is fine when very few are affected and they are random. Dropping columns makes sense when most values are missing. Some models, such as HistGradientBoostingClassifier, handle missing values natively, so imputation becomes optional.

  • Median for skewed numeric columns
  • Most frequent or a constant like "unknown" for categories
  • add_indicator=True keeps the missingness signal
  • Check df.isna().mean() before deciding

Encoding categories

One-hot encoding creates a 0/1 column per category, which suits unordered categories such as region or plan. Use OneHotEncoder(handle_unknown="ignore") so a category first seen in production becomes all zeros instead of an error. For categories with many rare values, min_frequency groups the rare ones, and handle_unknown="infrequent_if_exist" sends unseen values to that group.

OrdinalEncoder maps categories to integers. Use it for truly ordered values such as small, medium and large, by passing the order explicitly, or with tree models, which cope with arbitrary integer codes. Avoid integer codes for unordered categories in linear models: they imply that category 3 is three times category 1. For very high-cardinality columns such as postcodes, TargetEncoder is an option, and it uses internal cross-fitting to limit leakage.

Scaling and outliers

StandardScaler subtracts the training mean and divides by the training standard deviation. MinMaxScaler maps the training range to 0 to 1, so one extreme value squashes everything else. RobustScaler uses the median and interquartile range, which ignore extremes. Scale for k-nearest neighbours, SVMs, regularised linear models and neural networks; trees and tree ensembles do not need it.

Treat outliers as a decision, not a reflex. First check whether a value is an error, such as an age of 250, and fix or remove it at the data source. Real but extreme values, such as a few very large orders, can be clipped at a high training percentile, log-transformed, or left alone with robust scaling. Write down which you chose and why, because fraud and failures often live in the tail.

CompareChoosing a scaler
StandardScaler
  • Mean 0, SD 1
  • Good default
  • Sensitive to extreme values
MinMaxScaler
  • Range 0 to 1
  • Keeps zeros in sparse data
  • One outlier squashes the rest
RobustScaler
  • Median and IQR
  • Ignores extremes when scaling
  • Outliers stay large, not removed

Fit on training data only

Split first, then fit. Calling pipeline.fit(X_train, y_train) makes each transformer learn its statistics from training rows and passes the transformed data to the model. Calling pipeline.predict(X_test) only transforms the test rows with those learned values.

The pipeline also protects cross-validation. When you pass the whole pipeline to cross_val_score or GridSearchCV, the transformers are refitted inside each fold, so the held-out fold never influences the imputer or scaler. Preprocessing the full dataset first and then cross-validating leaks a little information into every fold. The leak is often small with scaling but can be large with feature selection or target encoding.

SequenceWho learns from which rows
Training rows
Pipeline
Test rows
  1. 1fit: learn medians, categories, means
    Training rows to Pipeline: fit: learn medians, categories, means
  2. 2fit: train the model on transformed rows
    Training rows to Pipeline: fit: train the model on transformed rows
  3. 3predict: send raw test rows
    Test rows to Pipeline: predict: send raw test rows
  4. 4transform with training statistics only
    Pipeline to Test rows: transform with training statistics only
  5. 5return predictions
    Pipeline to Test rows: return predictions

Learn it in 5 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Impute missing values~40m
  2. 2
    Encode categorical features~40m
  3. 3
    Scale numeric features~40m
  4. 4
    Handle outliers deliberately~40m
  5. 5
    Fit transforms on training data only~40m

Key points

  • Impute missing values with a statistic learned from the training data, and consider a missing-indicator column.
  • One-hot encode unordered categories; set handle_unknown="ignore" so new categories do not crash predictions.
  • Scale numeric features for distance-based and gradient-based models; trees do not need it.
  • Handle outliers on purpose: fix errors, clip extremes, or use robust scaling, and write down why.
  • Fit the pipeline on training data only, then call predict on test data so no test statistics leak in.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

num = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())
cat = make_pipeline(SimpleImputer(strategy="most_frequent"), OneHotEncoder(handle_unknown="ignore"))
pre = ColumnTransformer([("num", num, ["age", "income"]), ("cat", cat, ["plan", "region"])])
model = Pipeline([("pre", pre), ("clf", LogisticRegression(max_iter=1000))])

model.fit(X_train, y_train)          # learns medians, scales, categories from training only
print(model.score(X_test, y_test))   # test rows are only transformed, never fitted

X_train and X_test are pandas DataFrames with these four columns.

A complete mixed-type pipeline on synthetic customer data

Step 1: build a small synthetic DataFrame with missing ages, a plan category and a skewed spend column. Step 2: split before fitting. Step 3: define numeric and categorical branches. Step 4: fit on training rows and score on test rows. Expected evidence: no errors despite NaN values, and get_feature_names_out() listing scaled numeric columns plus one column per plan.

python
import numpy as np, pandas as pd
from sklearn.compose import ColumnTransformer; from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split; from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, RobustScaler
rng = np.random.default_rng(0); n = 400
df = pd.DataFrame({"age": rng.normal(40, 12, n), "spend": rng.lognormal(3, 1, n),
                   "plan": rng.choice(["basic", "plus", "pro"], n)})
df.loc[rng.choice(n, 40, replace=False), "age"] = np.nan
y = (df["plan"] == "pro") | (df["spend"] > 40)
pre = ColumnTransformer([("num", make_pipeline(SimpleImputer(strategy="median", add_indicator=True), RobustScaler()), ["age", "spend"]),
                         ("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"])])
Xa, Xb, ya, yb = train_test_split(df, y, random_state=0)
m = make_pipeline(pre, LogisticRegression(max_iter=1000)).fit(Xa, ya)
print(round(m.score(Xb, yb), 3), pre.get_feature_names_out())

Showing the leak from scaling before splitting

Step 1: on a dataset where the test rows come from a shifted range, scale everything first, then split. Step 2: do it correctly with a pipeline. Step 3: compare the scaler's learned mean. In the leaky version, the mean includes test rows, so the test set has quietly shaped the training inputs. With plain scaling the score difference is often small, but the habit matters: the same mistake with feature selection or target encoding can inflate scores a lot.

python
import numpy as np
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
train = rng.normal(0, 1, (80, 1))
test = rng.normal(3, 1, (20, 1))          # future data drifted upwards

leaky = StandardScaler().fit(np.vstack([train, test]))
safe = StandardScaler().fit(train)
print("leaky mean:", leaky.mean_.round(2))  # pulled towards the test data
print("safe mean:", safe.mean_.round(2))    # training data only

Quick reference

  • Split first; fit every transformer on X_train only
  • SimpleImputer(strategy="median", add_indicator=True) for numeric gaps
  • OneHotEncoder(handle_unknown="ignore") for unordered categories
  • Scale for k-NN, SVM, linear and neural models; trees do not need it
  • RobustScaler uses median and IQR; outliers stay large but do not distort the scale
  • ColumnTransformer drops unlisted columns by default (remainder="drop")
  • Pass the whole pipeline to cross_val_score so each fold refits preprocessing

Common mistakes

  • Calling fit_transform on the whole dataset before splitting, which leaks test statistics into training.
  • Dropping every row with a missing value, which can throw away much of the data and bias what is left.
  • Deleting outliers automatically when some of them are the rare cases you most need to predict.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Where should the imputer learn the median from?

Question 2

2A category appears in production that was never seen in training. Which setting prevents an error?

Question 3

3Which model gains least from feature scaling?

Question 4

4Why use add_indicator=True when imputing?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Given a DataFrame df, print the share of missing values per column and the number of distinct values in each text column.

  2. Exercise 2medium

    Build a ColumnTransformer that median-imputes and standard-scales age and income, and one-hot encodes city with unknown categories ignored. Fit it on training data and print the output feature names.

  3. Exercise 3hard

    Use GridSearchCV on a full preprocessing plus LogisticRegression pipeline to choose between median and mean imputation and C in 0.1, 1 and 10, with 5-fold cross-validation on training data only.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I scale data before or after splitting?
After. Split first, then fit the scaler on the training data and apply it to the test data, ideally inside a Pipeline so it happens automatically.
Is it OK to drop rows with missing values?
Only when very few rows are affected and the gaps are random. Otherwise you lose data and can bias the sample, so imputing with an indicator column is usually safer.
What is the difference between OneHotEncoder and OrdinalEncoder?
OneHotEncoder makes one 0/1 column per category and suits unordered values. OrdinalEncoder maps categories to integers, which suits ordered values or tree models.
Do I need to remove outliers?
Not automatically. Fix values that are errors, and decide case by case for real extremes: clip, transform, use robust scaling, or keep them if they are the cases you care about.

Go deeper

ShareXLinkedInWhatsApp