df = pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0], "c": [7.0, 8.0, 9.0]})
df| a | b | c | |
|---|---|---|---|
| 0 | 1.0 | 4.0 | 7.0 |
| 1 | 2.0 | 5.0 | 8.0 |
| 2 | 3.0 | 6.0 | 9.0 |
Add the pairwise product of every pair of selected columns.
Usage
For every unordered pair among the selected columns, adds one column holding their elementwise product, named by joining the two source names with sep. n selected columns produce n * (n - 1) / 2 interaction columns.
This step is pairwise only: it does not build 3-way-or-higher interaction terms. A user who needs one can write it explicitly with StepMutate.
See Arithmetic in Feature Engineering A to Z for background on products of columns (feature crosses).
See Arguments shared across steps for the arguments this step shares with the others.
columns: SelectorColumns to interact. Accepts a single column name, a list of names, a mlfeatures selector such as Selectors.numeric_features() (see Selectors for the full set), or a narwhals or polars selector (narwhals.selectors.numeric(), polars.selectors.numeric()). Selectors are resolved against the data frame’s schema when the recipe is fitted, so the same selector works on any backend. Only numeric columns are meaningful here.
sep: str = "x"Separator joining each pair’s two column names into the output column name. Default "_x_".
keep_original_cols: bool = FalseIf True, the source columns are kept alongside the interaction columns instead of being dropped. Default False.
role: str | None = "feature"Role assigned to the new interaction columns (see Roles). Default "feature".
id: str | None = None"interact"; a second step of this type in the same recipe becomes "interact_2", and passing an id already used in the recipe is an error.
Every pair of the three numeric columns gets its own product column:
| a | b | c | |
|---|---|---|---|
| 0 | 1.0 | 4.0 | 7.0 |
| 1 | 2.0 | 5.0 | 8.0 |
| 2 | 3.0 | 6.0 | 9.0 |
Specifying the step touches no data:
Recipe (untrained)
Inputs: no roles assigned
Steps:
step_interact(select(role='feature', type=NumericType)) [untrained]
fit() records the pairs to interact:
Recipe (trained)
Inputs: 3 columns (3 features)
Steps:
step_interact(a, b, c → a_x_b, a_x_c, b_x_c) [trained]
transform() adds one product column per pair and drops the sources:
A custom sep changes the generated names:
recipe = Recipe().add(StepInteract(s.numeric_features(), sep="_times_"))
fitted = recipe.fit(df)
fitted.transform(df)| a_times_b | a_times_c | b_times_c | |
|---|---|---|---|
| 0 | 4.0 | 7.0 | 28.0 |
| 1 | 10.0 | 16.0 | 40.0 |
| 2 | 18.0 | 27.0 | 54.0 |
keep_original_cols keeps the source columns alongside the products: