df = pd.DataFrame({"color": ["red", "green", "blue", "red"]})
df| color | |
|---|---|
| 0 | red |
| 1 | green |
| 2 | blue |
| 3 | red |
Expand categorical columns into k-1 binary indicator columns.
Usage
Each selected column is replaced by k-1 indicator columns where k is the number of unique non-null levels seen during fit(). Indicators are nw.Int8 (0/1); a column that contains null-source or unseen-level rows is nw.Float64 instead (0.0/1.0/NaN), since pandas’ Int8 cannot hold the missing values. The first level in ascending sort order is the reference level and is dropped. To keep an indicator for every level, use StepOneHot instead.
See Dummy Encoding in Feature Engineering A to Z for background on this technique.
See Arguments shared across steps for the arguments this step shares with the others.
columns: SelectorColumns to expand. Accepts a single column name, a list of names, a mlfeatures selector such as Selectors.nominal_features() (see Selectors for the full set), or a narwhals or polars selector (narwhals.selectors.string(), polars.selectors.string()). Selectors are resolved against the data frame’s schema when the recipe is fitted, so the same selector works on any backend. Only discrete columns (string, categorical, enum, boolean, and integer) are meaningful here.
name_fn: Callable[[str, str], str] | None = NoneCallable mapping (source_column, level_as_str) to the indicator column’s name. Default None, which names them "{column}_{level}".
keep_original_cols: bool = FalseIf True, the source columns are kept alongside the indicators instead of being dropped. Default False.
role: str | None = "feature"Role assigned to the indicator columns (see Roles). Default "feature".
id: str | None = None"dummy"; a second step of this type in the same recipe becomes "dummy_2", and passing an id already used in the recipe is an error.
Each categorical column is replaced by k-1 indicators; the first level in sort order (blue) is the dropped reference:
Specifying the step touches no data:
Recipe (untrained)
Inputs: no roles assigned
Steps:
step_dummy(select(role='feature', type=(String, Categorical, Enum))) [untrained]
fit() records the levels of each selected column:
Recipe (trained)
Inputs: 2 columns (2 features)
Steps:
step_dummy(color → color_green, color_red) [trained]
transform() replaces the column with its indicators:
keep_original_cols keeps the source column alongside them: