Feature engineering for numeric and categorical data

scikit-learn 1.9.1

Choose features available at prediction time and fit column-specific transforms inside a pipeline.

On this page

Design features around prediction time

Start with fields available when a prediction must be made. Logically useful features can include ratios, totals, or calendar parts. Compute historical aggregates from earlier data only. Apply the same feature definitions at training and inference time.

Impute, scale, and encode by column

ColumnTransformer applies different transformations to column groups. Use an imputer for missing values when appropriate. OneHotEncoder can ignore unknown categories for inference. Fit the transformer together with the estimator during validation.

import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

train = pd.DataFrame({"price": [2.0, 3.0, None, 8.0, 9.0, 7.0],
                      "store": ["A", "B", "A", "B", "A", "B"]})
preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["price"]),
    ("store", OneHotEncoder(handle_unknown="ignore"), ["store"]),
])
model = make_pipeline(preprocess, LogisticRegression())
model.fit(train, [0, 0, 0, 1, 1, 1])
new = pd.DataFrame({"price": [5.0], "store": ["C"]})
print(model.predict_proba(new).shape)
Example output
(1, 2)

Official references