Skip to main content

StepMutate

Apply arbitrary column expressions: the escape hatch.

Usage

Source

StepMutate(
    mutations,
    *,
    role="feature",
    id=None,
)

Each supplied mutation either adds a new column or overwrites an existing one, so the exact column change is only known after the mutations run on the training data frame. fit() applies them once to read off which columns were added (and their dtypes) versus modified in place, then re-applies the same expressions at transform time. To remove rows instead, see StepFilter.

New columns are attributed to no declared parents (output_parents maps each to []): the expressions are opaque callables, so mlfeatures does not try to infer which inputs a mutation read. This is the deliberate trade-off of an escape hatch: full flexibility, coarse lineage.

See Arguments shared across steps for the arguments this step shares with the others.

Parameters

mutations: Mapping[str, Mutation]

Mapping from output column name to a callable taking the data frame and returning that column’s value (a narwhals expression or series). Must be a non-empty dict of str names to callables.

role: str | None = "feature"

Role assigned to any new columns the mutations create (see Roles). Columns overwritten in place keep their existing role. Default "feature".

id: str | None = None
Stable step identifier. Defaults to "mutate"; a second step of this type in the same recipe becomes "mutate_2", and passing an id already used in the recipe is an error.

Examples

x_sq is added from an expression over x; x itself is overwritten in place:

df = pd.DataFrame({"x": [1.0, 2.0, 3.0]})
df
x
0 1.0
1 2.0
2 3.0

Specifying the step touches no data:

recipe = Recipe().add(
    StepMutate({"x_sq": lambda df: df["x"] ** 2, "x": lambda df: df["x"] + 1})
)
recipe
Recipe (untrained)
  Inputs: no roles assigned
  Steps:
    step_mutate()  [untrained]

fit() runs the mutations once on the training data frame to read off which columns they add and with what dtypes:

fitted = recipe.fit(df)
fitted
Recipe (trained)
  Inputs: 2 columns (2 features)
  Steps:
    step_mutate(x → x_sq)  [trained]

transform() applies them together, so every mutation sees the original data frame; x_sq squares the incoming x, not the overwritten one:

fitted.transform(df)
x x_sq
0 2.0 1.0
1 3.0 4.0
2 4.0 9.0