typestar

Different columns, different treatment in Python

ColumnTransformer routes numeric and categorical columns down separate paths.

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler

prepare = ColumnTransformer(
    transformers=[
        ("numeric", StandardScaler(), [0, 1]),
        ("categorical", OneHotEncoder(handle_unknown="ignore"), [2]),
    ],
    remainder="drop",
)

rows = [[1.0, 10.0, "red"], [2.0, 20.0, "blue"], [3.0, 30.0, "red"]]
out = prepare.fit_transform(rows)

print(out.shape)
print(prepare.get_feature_names_out())

How it works

  1. Each entry is (name, transformer, columns).
  2. OneHotEncoder turns categories into indicator columns.
  3. remainder decides what happens to columns you did not name.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
439
Tokens
120
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 3 of 4 in Preprocessing, step 6 of 25 in Machine learning with scikit-learn.

← Previous Next →