Skip to main content
Albero Academy

ColumnTransformer

Apply different preprocessing to different columns.

Preprocessing8 min

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

numeric vs categorical
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
pre = ColumnTransformer([
("num", StandardScaler(), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city", "grade"]),
])
# Combine with a model in one pipeline
from sklearn.pipeline import make_pipeline
from sklearn.ensemble import RandomForestClassifier
model = make_pipeline(pre, RandomForestClassifier())
model.fit(X_train, y_train)

Key takeaways

  1. 01ColumnTransformer applies different transformers to different columns.
  2. 02Typical setup: scale numeric columns, one-hot encode categorical ones.
  3. 03Wrap it in a Pipeline with a model for a single end-to-end estimator.
  4. 04This ColumnTransformer + Pipeline pattern is the standard for real tabular ML.

Finished this chapter?

Mark it complete to track your progress through Scikit-learn.