TExcelTAD
Home › Machine Learning › ColumnTransformer

ColumnTransformer

Real tables mix column types: numbers that need imputing and scaling, categories that need one-hot encoding, maybe text or dates. A plain Pipeline applies every step to all columns. ColumnTransformer applies different preprocessing to different columns and glues the results back together — and it fits neatly inside a pipeline.

The data

An invented table of 16 gym members: will they cancel their membership (churn)?

python · try it yourself
import io
import pandas as pd

csv = """age,monthly_fee,visits_per_week,plan,city,churn
34,29.9,3,basic,Bern,0
51,49.9,1,premium,Basel,1
23,19.9,,student,Bern,0
45,49.9,4,premium,Zurich,0
38,29.9,0,basic,Basel,1
29,,2,basic,Zurich,0
62,49.9,1,premium,Bern,1
21,19.9,5,student,Zurich,0
40,29.9,1,basic,,1
33,49.9,3,premium,Basel,0
27,19.9,0,student,Basel,1
55,29.9,2,basic,Bern,0
47,49.9,0,premium,Zurich,1
31,29.9,4,basic,Zurich,0
25,19.9,1,student,Bern,1
58,29.9,3,basic,Basel,0"""
gym = pd.read_csv(io.StringIO(csv))
print(gym.head())
print("missing:", gym.isna().sum()[gym.isna().sum() > 0].to_dict())
   age  monthly_fee  visits_per_week     plan    city  churn
0   34         29.9              3.0    basic    Bern      0
1   51         49.9              1.0  premium   Basel      1
2   23         19.9              NaN  student    Bern      0
3   45         49.9              4.0  premium  Zurich      0
4   38         29.9              0.0    basic   Basel      1
missing: {'monthly_fee': 1, 'visits_per_week': 1, 'city': 1}

Three numeric columns (with some gaps), two categorical columns (one with a gap), and the target.

Building the preprocessor

Each entry of a ColumnTransformer is (name, transformer, columns). Numeric columns get median imputation plus scaling; categorical columns get most-frequent imputation plus one-hot encoding:

python · try it yourself
import io
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder

csv = """age,monthly_fee,visits_per_week,plan,city,churn
34,29.9,3,basic,Bern,0
51,49.9,1,premium,Basel,1
23,19.9,,student,Bern,0
45,49.9,4,premium,Zurich,0
38,29.9,0,basic,Basel,1
29,,2,basic,Zurich,0
62,49.9,1,premium,Bern,1
21,19.9,5,student,Zurich,0
40,29.9,1,basic,,1
33,49.9,3,premium,Basel,0
27,19.9,0,student,Basel,1
55,29.9,2,basic,Bern,0
47,49.9,0,premium,Zurich,1
31,29.9,4,basic,Zurich,0
25,19.9,1,student,Bern,1
58,29.9,3,basic,Basel,0"""
gym = pd.read_csv(io.StringIO(csv))
X = gym.drop(columns="churn")

numeric = ["age", "monthly_fee", "visits_per_week"]
categorical = ["plan", "city"]

preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", make_pipeline(SimpleImputer(strategy="most_frequent"),
                          OneHotEncoder(handle_unknown="ignore")), categorical),
])
Xt = preprocess.fit_transform(X)
print("shape after preprocessing:", Xt.shape)
print(list(preprocess.get_feature_names_out()))
print(pd.DataFrame(Xt, columns=preprocess.get_feature_names_out()).head(3).round(2).to_string())
shape after preprocessing: (16, 9)
['num__age', 'num__monthly_fee', 'num__visits_per_week', 'cat__plan_basic', 'cat__plan_premium', 'cat__plan_student', 'cat__city_Basel', 'cat__city_Bern', 'cat__city_Zurich']
   num__age  num__monthly_fee  num__visits_per_week  cat__plan_basic  cat__plan_premium  cat__plan_student  cat__city_Basel  cat__city_Bern  cat__city_Zurich
0     -0.37             -0.32                  0.67              1.0                0.0                0.0              0.0             1.0               0.0
1      0.98              1.39                 -0.67              0.0                1.0                0.0              1.0             0.0               0.0
2     -1.25             -1.18                  0.00              0.0                0.0                1.0              0.0             1.0               0.0

The 5 input columns became 9: 3 scaled numbers plus 6 one-hot columns. Feature names are prefixed with the transformer name (num__, cat__).

The full model

Put the preprocessor and a classifier into one pipeline. Now raw DataFrames — with missing values and text — go straight in:

python · try it yourself
import io
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

csv = """age,monthly_fee,visits_per_week,plan,city,churn
34,29.9,3,basic,Bern,0
51,49.9,1,premium,Basel,1
23,19.9,,student,Bern,0
45,49.9,4,premium,Zurich,0
38,29.9,0,basic,Basel,1
29,,2,basic,Zurich,0
62,49.9,1,premium,Bern,1
21,19.9,5,student,Zurich,0
40,29.9,1,basic,,1
33,49.9,3,premium,Basel,0
27,19.9,0,student,Basel,1
55,29.9,2,basic,Bern,0
47,49.9,0,premium,Zurich,1
31,29.9,4,basic,Zurich,0
25,19.9,1,student,Bern,1
58,29.9,3,basic,Basel,0"""
gym = pd.read_csv(io.StringIO(csv))
X, y = gym.drop(columns="churn"), gym["churn"]

preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
     ["age", "monthly_fee", "visits_per_week"]),
    ("cat", make_pipeline(SimpleImputer(strategy="most_frequent"),
                          OneHotEncoder(handle_unknown="ignore")), ["plan", "city"]),
])
model = make_pipeline(preprocess, LogisticRegression())

print("CV accuracy:", cross_val_score(model, X, y, cv=4).mean().round(3))

model.fit(X, y)
new_members = pd.DataFrame({
    "age": [36, 24], "monthly_fee": [49.9, None], "visits_per_week": [0, 4],
    "plan": ["premium", "student"], "city": ["Geneva", "Bern"],     # Geneva never seen
})
print("churn probability:", model.predict_proba(new_members)[:, 1].round(2))
CV accuracy: 0.812
churn probability: [0.9  0.05]

The new members include a missing fee and an unseen city — the pipeline handles both without complaint. The premium member who never comes to the gym gets a high churn probability; the keen student a low one.

Selecting columns by type

Listing columns by hand is fine for small tables. make_column_selector picks them by dtype instead, and make_column_transformer names the steps automatically:

python · try it yourself
import pandas as pd
from sklearn.compose import make_column_transformer, make_column_selector
from sklearn.preprocessing import StandardScaler, OneHotEncoder

df = pd.DataFrame({
    "height": [1.72, 1.65, 1.80],
    "weight": [70, 58, 85],
    "sport": ["tennis", "golf", "tennis"],
})
ct = make_column_transformer(
    (StandardScaler(), make_column_selector(dtype_include="number")),
    (OneHotEncoder(), make_column_selector(dtype_include="object")),
)
print(ct.fit_transform(df).round(2))
print(ct.get_feature_names_out())
[[-0.05 -0.09  0.    1.  ]
 [-1.2  -1.18  1.    0.  ]
 [ 1.25  1.27  0.    1.  ]]
['standardscaler__height' 'standardscaler__weight'
 'onehotencoder__sport_golf' 'onehotencoder__sport_tennis']

remainder: what happens to unlisted columns?

By default, columns not mentioned in any transformer are dropped (remainder="drop"). Use remainder="passthrough" to keep them unchanged:

python · try it yourself
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

df = pd.DataFrame({"colour": ["red", "blue"], "size": [3, 5], "id": [101, 102]})
for remainder in ["drop", "passthrough"]:
    ct = ColumnTransformer([("cat", OneHotEncoder(), ["colour"])], remainder=remainder)
    print(remainder, "->", ct.fit_transform(df).tolist(), list(ct.get_feature_names_out()))
drop -> [[0.0, 1.0], [1.0, 0.0]] ['cat__colour_blue', 'cat__colour_red']
passthrough -> [[0.0, 1.0, 3.0, 101.0], [1.0, 0.0, 5.0, 102.0]] ['cat__colour_blue', 'cat__colour_red', 'remainder__size', 'remainder__id']

Test yourself

What does ColumnTransformer let you do that a plain Pipeline doesn't?

  1. Train several models at once
  2. Apply different preprocessing to different columns
  3. Skip the fit step
  4. Use more than one CPU

By default, what happens to columns not listed in any transformer?

  1. They are kept unchanged
  2. They are dropped
  3. They are one-hot encoded
  4. An error is raised

A new sample contains a category never seen in training. Which setting prevents an error?

  1. StandardScaler(with_mean=False)
  2. OneHotEncoder(handle_unknown='ignore')
  3. SimpleImputer(strategy='mean')
  4. remainder='passthrough'