Using scikit-learn Pipeline and ColumnTransformer for Mixed-type Data
Combine numeric, categorical and text columns in a single scikit-learn Pipeline to avoid data leakage and keep preprocessing consistent across CV folds.
21 Jan 2026, 07:59 UTC

The Challenge of Mixed Data Types
Real world tables contain numbers, categories and free‑text columns. Applying a single scaler or encoder to the whole matrix either fails or silently corrupts the data, and fitting before a train‑test split leaks information.
Designing a Single Pipeline with ColumnTransformer
A Pipeline chains estimators; ColumnTransformer lets you specify a different transformer for each column group. The steps are fitted only on the training split, so no leakage occurs.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
numeric_features = ['age']
categorical_features = ['city']
text_features = ['notes']
numeric_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())
])
categorical_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
text_transformer = TfidfVectorizer(max_features=1000)
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features),
('txt', text_transformer, text_features)
],
remainder='drop' # discard any columns not listed
)
clf = Pipeline(steps=[
('preprocessor', preprocessor),
('classifier', LogisticRegression(max_iter=1000))
])
clf.fit(X_train, y_train) # X_train and y_train are assumed defined
After fit, clf.predict applies the same imputation, scaling, encoding and vectorization learned from the training data only.
Verification, Persistence and Hyperparameter Search
Call clf.predict(X_test) before and after serializing with joblib.dump and joblib.load; the results should match if serialization succeeded.
When using GridSearchCV, target nested steps with double underscores, e.g. 'classifier__C': [0.1, 1.0]. The best estimator retains the fitted preprocessor unchanged.
Version Requirements and a Practical Limitation
ColumnTransformer was added in scikit‑learn 0.20 and its API stabilized in 0.24. Earlier versions require manual looping over column groups.
A common issue arises when a transformer returns a sparse matrix (e.g., OneHotEncoder(sparse_output=True)) while another returns a dense array. The horizontal stacking can fail if dtypes are incompatible; ensure compatible dtypes or force dense output if the data size permits.
Actionable Closing
Replace any fit_transform performed on the full dataset before splitting with a Pipeline that contains a ColumnTransformer. Start with numeric and categorical branches, add a text branch only if needed, verify the output shape after fit_transform, and use joblib to persist the model safely.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.