Skip to main content

StepUnknown

Recode missing categorical levels to an explicit "unknown" level.

Usage

Source

StepUnknown(
    columns,
    *,
    new_level=DEFAULT_UNKNOWN_LEVEL,
    id=None,
)

Each selected categorical column has its nulls replaced in place by new_level. To also pool infrequent levels, see StepOther.

See Simple Imputation 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 recode. 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 categorical columns (string, categorical, and enum) are meaningful here.

new_level: str = DEFAULT_UNKNOWN_LEVEL

The level that replaces nulls. Default "unknown". A UserWarning is emitted if a selected column already contains this level, since the recoded rows then become indistinguishable from real ones.

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

Examples

Nulls in the selected column are recoded in place to an explicit "unknown" level:

df = pd.DataFrame(
    {"city": pd.Series(["NYC", "LA", "NYC", None], dtype="category")}
)
df
city
0 NYC
1 LA
2 NYC
3 NaN

Specifying the step touches no data:

recipe = Recipe().add(StepUnknown(s.nominal_features()))
recipe
Recipe (untrained)
  Inputs: no roles assigned
  Steps:
    step_unknown(select(role='feature', type=(String, Categorical, Enum)))  [untrained]

fit() records the level to add to each column:

fitted = recipe.fit(df)
fitted
Recipe (trained)
  Inputs: 1 columns (1 feature)
  Steps:
    step_unknown(city)  [trained]

transform() recodes the nulls in place:

fitted.transform(df)
city
0 NYC
1 LA
2 NYC
3 unknown

new_level names the added level:

recipe = Recipe().add(StepUnknown(s.nominal_features(), new_level="missing"))
fitted = recipe.fit(df)
fitted.transform(df)
city
0 NYC
1 LA
2 NYC
3 missing