Preprocess Mixed Tabular Data with scikit-learn Pipeline and ColumnTransformer
Wrap preprocessing and modeling in one scikit-learn Pipeline to prevent leakage and ship a single serializable estimator.
21 Jun 2026, 02:17 UTC

The problem and the practical answer
You have a table with numeric columns, such as age or fare, and categorical columns, such as port of embarkation or sex. If you scale the numeric columns and encode the categorical columns before splitting into training and test sets, the scaler learns from test rows too. That is data leakage, and it makes validation scores look better than they will be in production. At inference time, you must also reproduce the same column order and encoding by hand, which is a common source of silent mismatches.
The useful takeaway is to wrap a ColumnTransformer inside a Pipeline, fit only on training data, and serialize the complete object with joblib. A Pipeline is a sequential estimator that applies transformers and then a final model. A ColumnTransformer routes different columns to different transformers and concatenates the results. Serialization means saving the fitted object to disk so it can be reloaded later.
How the pieces fit together
ColumnTransformer accepts a list of (name, transformer, columns) tuples. Numeric columns go to StandardScaler, which centers and scales values using the mean and standard deviation learned during fitting. Categorical columns go to OneHotEncoder, which converts each category into a binary column. By default, columns not listed in any transformer are dropped, so you must either list every input column or set remainder='passthrough'.
The outer Pipeline fits the preprocessor on training data, transforms that same training data, fits the final estimator on the transformed result, and stores every fitted parameter. Because the scaler and encoder never see test data during fitting, there is no leakage from preprocessing. Because the preprocessor is inside the pipeline, inference code can call predict on raw, unprocessed rows.
Worked configuration
Run this in a Python environment where scikit-learn, pandas, and joblib are installed. No special operating-system permissions are required unless you write to a protected directory; make sure the output path is writable. Replace your_data.csv and target with your actual file and label column.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.ensemble import RandomForestClassifier
import joblib
df = pd.read_csv("your_data.csv")
X = df.drop(columns=["target"])
y = df["target"]
numeric_features = ["age", "fare"]
categorical_features = ["embarked", "sex"]
preprocessor = ColumnTransformer(
transformers=[
("num", StandardScaler(), numeric_features),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical_features),
],
remainder="drop",
)
clf = Pipeline(
steps=[
("preprocess", preprocessor),
("model", RandomForestClassifier(random_state=42)),
]
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
clf.fit(X_train, y_train)
# Persist transformers and model in one file.
joblib.dump(clf, "trained_pipeline.joblib")
The call to clf.fit changes state in memory by fitting the scaler, encoder, and random forest. joblib.dump writes that state to disk and will overwrite an existing file at the same path. Keep a copy of the previous file if you need to revert to an earlier model version.
What to check after fitting
- Confirm that predictions work on raw test rows without manual preprocessing:
predictions = clf.predict(X_test)
print(predictions[:5])
- Reload the pipeline in a new Python process and verify it is self-contained:
loaded = joblib.load("trained_pipeline.joblib")
reload_predictions = loaded.predict(X_test)
If reload_predictions matches predictions, the saved object includes preprocessing and the model.
- Check the transformed width. The number of output columns should equal the number of numeric features plus the total number of one-hot categories across the categorical features:
transformed = preprocessor.fit_transform(X_train)
expected_width = len(numeric_features) + sum(
X_train[col].nunique() for col in categorical_features
)
assert transformed.shape[1] == expected_width
Do not fit preprocessor on the full X before splitting. Fitting on the full dataset lets test-row statistics influence the scaler and lets test categories influence the encoder, which overstates validation performance.
Limits and common mistakes
OneHotEncoder raises an error by default when it encounters a category at inference that was not present during training. Setting handle_unknown="ignore" produces an all-zero row for that category instead, which is safer for production. However, ignored categories still contribute no signal, so monitor how often they appear in live data.
By default, ColumnTransformer drops any column you do not explicitly assign. If your DataFrame gains a new feature and you forget to add it to numeric_features or categorical_features, the pipeline will silently exclude it. Consider setting remainder="passthrough" only if you intentionally want unlisted columns passed through unchanged.
A Pipeline does not perform hyperparameter search by itself. To tune the model or preprocessing parameters, wrap the pipeline in GridSearchCV or RandomizedSearchCV and pass parameter names such as model__n_estimators or preprocess__num__with_mean.
Positional column indices are fragile: if the input DataFrame column order changes, integer-based column selection breaks silently. Prefer column names wherever possible.
Practical verification for leakage
Run cross_val_score with the pipeline on training data only. Then manually preprocess the full dataset outside any split and train a model on it. If the manually preprocessed full-dataset score is substantially higher than the cross-validated pipeline score, leakage is likely in the manual approach, not in the pipeline.
There is no rollback operation for an in-memory fit. If joblib.dump overwrites a file you still need, restore it from your previous backup; the pipeline itself does not modify source data.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.