Skip to main content

StepDummy

Expand categorical columns into k-1 binary indicator columns.

Usage

Source

StepDummy(
    columns,
    *,
    name_fn=None,
    keep_original_cols=False,
    role="feature",
    id=None
)

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.

Parameters

columns: Selector

Columns 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 = None

Callable mapping (source_column, level_as_str) to the indicator column’s name. Default None, which names them "{column}_{level}".

keep_original_cols: bool = False

If 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
Stable step identifier. Defaults to "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.

Examples

Each categorical column is replaced by k-1 indicators; the first level in sort order (blue) is the dropped reference:

df = pd.DataFrame({"color": ["red", "green", "blue", "red"]})
df
color
0 red
1 green
2 blue
3 red

Specifying the step touches no data:

recipe = Recipe().add(StepDummy(s.nominal_features()))
recipe
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:

fitted = recipe.fit(df)
fitted
Recipe (trained)
  Inputs: 2 columns (2 features)
  Steps:
    step_dummy(color → color_green, color_red)  [trained]

transform() replaces the column with its indicators:

fitted.transform(df)
color_green color_red
0 0 1
1 1 0
2 0 0
3 0 1

keep_original_cols keeps the source column alongside them:

recipe = Recipe().add(StepDummy(s.nominal_features(), keep_original_cols=True))
fitted = recipe.fit(df)
fitted.transform(df)
color color_green color_red
0 red 0 1
1 green 1 0
2 blue 0 0
3 red 0 1