Pipeline and ColumnTransformer
Quick answer
A Pipeline chains transformations and a final estimator, so fitting and prediction follow the same sequence. ColumnTransformer applies separate transformations to selected columns and combines their outputs. Together they keep training preprocessing and inference preprocessing consistent. All library examples are standalone local Python examples tested with scikit-learn 1.8.0; ByteMind package execution is not verified.
Combine numeric and categorical columns
import pandas as pdfrom sklearn.compose import ColumnTransformerfrom sklearn.preprocessing import StandardScaler, OneHotEncoderX = pd.DataFrame({'weight': [2, 6], 'zone': ['A', 'B']})pre = ColumnTransformer([ ('num', StandardScaler(), ['weight']), ('cat', OneHotEncoder(handle_unknown='ignore', sparse_output=False), ['zone'])])print(pre.fit_transform(X).tolist())print(pre.transform(pd.DataFrame({'weight': [10], 'zone': ['C']})).tolist())Expected output:
[[-1.0, 1.0, 0.0], [1.0, 0.0, 1.0]][[3.0, 0.0, 0.0]]The unfamiliar zone does not create a fourth feature.
How it works
Pipeline takes named (name, estimator) pairs. Intermediate steps need fit and transform; the final step needs fit and must provide predict if prediction is requested. Calling pipeline.fit trains each intermediate transformer on the training representation and trains the final model on the transformed rows. Calling pipeline.predict applies the fitted transformations before predicting. ColumnTransformer takes (name, transformer, columns) triples; results are concatenated in declared order. By default unlisted columns are dropped; remainder="passthrough" keeps remaining fitted columns, so use an explicit schema to avoid accidental features. OneHotEncoder(handle_unknown="ignore") keeps output width fixed, encoding an unseen category as all zeros for that feature. This does not guarantee a reliable prediction for unfamiliar inputs. Sparse output depends on component outputs and sparse_threshold. When cross-validating, pass the whole unfitted pipeline so each fold learns its own transformations; preprocessing the complete dataset first leaks information.
Fit and predict through a pipeline
from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalerfrom sklearn.dummy import DummyRegressorp = Pipeline([('scale', StandardScaler()), ('model', DummyRegressor())])p.fit([[2], [6]], [10, 20])print(p.predict([[100]]).tolist())print(p.named_steps['scale'].mean_.tolist())Expected output:
[15.0][4.0]The pipeline uses the training scaler and the final constant predictor.
Common mistakes
Do not call preprocessing.fit_transform on all rows and then cross-validate the resulting matrix. Do not assume ColumnTransformer will enforce your application schema or detect a swapped numeric unit. Validate required columns, dtypes, units and availability independently. Inspect fitted steps via named_steps and named_transformers_; caching may clone intermediate transformers.
Practice
Use the milestone fixture. Predict how many one-hot columns remain when a third category appears at inference. Check that the fitted numeric mean and category list have not changed.
Reference candidate: concept-pipeline-and-columntransformer. Review the associated knowledge check. Native estimator tasks require a local scientific Python environment.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pipeline and ColumnTransformer — knowledge check
Apply estimator contracts and leakage-resistant pipelines to small fixtures.
What does Pipeline do at prediction time?
How are declared ColumnTransformer outputs combined?
What is the default remainder behavior?
How is an unknown category encoded with handle_unknown="ignore"?
What should be passed to cross-validation?