Skip to main content

Recipe.add_role()

Return a new recipe with a role added at this point in the chain.

Usage

Source

Recipe.add_role(
    columns,
    *,
    role,
)

Unlike set_roles(), which declares roles on the input columns whatever its position, a role operation takes effect where it is written: steps added after it see the new role, steps added before it do not. It can also reach columns that earlier steps created.

The columns are resolved when the recipe is fitted, against the columns as the steps before it left them. A selection matching nothing changes nothing. Adding a role a column already has is harmless; an incompatible one ("target" on a feature) raises when the recipe is fitted.

Wherever the call is written, a column that is only a feature by default (see Recipe) and is made the "target" or "case_weights" is taken out of the features instead of raising or keeping both roles, like set_roles(). A feature role you declared yourself is never taken away, so it still conflicts with "target". Adding the "feature" role never changes which other columns are features.

Parameters

columns: Selector

Columns to give the role to. 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 as the steps before this one left it, when the recipe is fitted.

role: str
The role to add.

Examples

Give Seniority a "group" role after the normalization, so the step before it is unaffected:

recipe = (
    Recipe(data=credit, target="Status")
    .add(StepNormalize(s.numeric_features()))
    .add_role(s.starts_with("Senior"), role="group")
)
recipe
Recipe (untrained)
  Inputs: 14 columns (1 target)
  Steps:
    step_normalize(select(role='feature', type=NumericType))  [untrained]
    add_role(starts_with('Senior'), role='group')

Fitting applies the role, which the summary then shows:

fitted = recipe.fit(credit)
fitted.summary()
shape: (14, 5)
namedtyperolessourcesparse
strstrstrstrbool
"Status""str""target""original"false
"Seniority""float""feature, group""original"false
"Home""str""feature""original"false
"Time""float""feature""original"false
"Age""float""feature""original"false
……………
"Income""float""feature""original"false
"Assets""float""feature""original"false
"Debt""float""feature""original"false
"Amount""float""feature""original"false
"Price""float""feature""original"false