Skip to main content

Recipe.update_role()

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

Usage

Source

Recipe.update_role(
    columns,
    *,
    new_role,
    old_role=None,
)

Takes effect where it is written (see add_role()). With old_role only that role is swapped for new_role and the column’s other roles stay; without it, all of a column’s roles are replaced by new_role.

Parameters

columns: Selector

Columns to change the role of. 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.

new_role: str

The role the columns end up with.

old_role: str | None = None
The role to replace. Every selected column must carry it, or fitting raises ValueError. Default None (replace all roles).

Examples

Normalize every numeric feature, then swap the "feature" role of Seniority for "id", so steps added after this call no longer select it:

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

Fitting applies the change, which the summary then shows:

fitted = recipe.fit(credit)
fitted.summary()
shape: (14, 5)
namedtyperolessourcesparse
strstrstrstrbool
"Status""str""target""original"false
"Seniority""float""id""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