## StepMutate


Apply arbitrary column expressions: the escape hatch.


Usage

``` python
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()](Step.fit.md#mlfeatures.Step.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](StepFilter.md#mlfeatures.StepFilter).

New columns are attributed to no declared parents ([output_parents](Step.output_parents.md#mlfeatures.Step.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](../user-guide/common-step-arguments.md) 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](Roles.md#mlfeatures.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:


``` python
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:


``` python
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()](Step.fit.md#mlfeatures.Step.fit) runs the mutations once on the training data frame to read off which columns they add and with what dtypes:


``` python
fitted = recipe.fit(df)
fitted
```


    Recipe (trained)
      Inputs: 2 columns (2 features)
      Steps:
        step_mutate(x → x_sq)  [trained]


[transform()](Step.transform.md#mlfeatures.Step.transform) applies them together, so every mutation sees the original data frame; `x_sq` squares the incoming `x`, not the overwritten one:


``` python
fitted.transform(df)
```


|     | x   | x_sq |
|-----|-----|------|
| 0   | 2.0 | 1.0  |
| 1   | 3.0 | 4.0  |
| 2   | 4.0 | 9.0  |
