df = pd.DataFrame({"color": ["red", "green", "blue", "red"]})
df| color | |
|---|---|
| 0 | red |
| 1 | green |
| 2 | blue |
| 3 | red |
Expand discrete columns into k binary indicator columns.
Usage
Each selected column is replaced by k 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. Unlike StepDummy, no reference level is dropped.
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"one_hot"; a second step of this type in the same recipe becomes "one_hot_2", and passing an id already used in the recipe is an error.
Each categorical column is replaced by one indicator per level, with no reference level dropped (contrast StepDummy):
Specifying the step touches no data:
Recipe (untrained)
Inputs: no roles assigned
Steps:
step_one_hot(select(role='feature', type=(String, Categorical, Enum))) [untrained]
fit() records the levels of each selected column:
Recipe (trained)
Inputs: 3 columns (3 features)
Steps:
step_one_hot(color → color_blue, color_green, color_red) [trained]
transform() replaces the column with one indicator per level:
keep_original_cols keeps the source column alongside them: