Real datasets mix numeric and categorical columns that need different preprocessing — scale the numbers, one-hot the categories. A ColumnTransformer applies the right transformer to the right columns in one step.
Per-column preprocessing
from sklearn.compose import ColumnTransformerfrom sklearn.preprocessing import StandardScaler, OneHotEncoderpre = ColumnTransformer([("num", StandardScaler(), ["age", "income"]),("cat", OneHotEncoder(handle_unknown="ignore"), ["city", "grade"]),])# Combine with a model in one pipelinefrom sklearn.pipeline import make_pipelinefrom sklearn.ensemble import RandomForestClassifiermodel = make_pipeline(pre, RandomForestClassifier())model.fit(X_train, y_train)
Key takeaways
- 01ColumnTransformer applies different transformers to different columns.
- 02Typical setup: scale numeric columns, one-hot encode categorical ones.
- 03Wrap it in a Pipeline with a model for a single end-to-end estimator.
- 04This ColumnTransformer + Pipeline pattern is the standard for real tabular ML.
