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
- Each entry is (name, transformer, columns).
OneHotEncoderturns categories into indicator columns.remainderdecides what happens to columns you did not name.
Keywords and builtins used here
print
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.
Step 3 of 4 in Preprocessing, step 6 of 25 in Machine learning with scikit-learn.