df = pd.DataFrame(
{"city": pd.Series(["NYC", "LA", "NYC", None], dtype="category")}
)
df| city | |
|---|---|
| 0 | NYC |
| 1 | LA |
| 2 | NYC |
| 3 | NaN |
Recode missing categorical levels to an explicit "unknown" level.
Usage
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.
columns: SelectorColumns 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"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.
Nulls in the selected column are recoded in place to an explicit "unknown" level:
| city | |
|---|---|
| 0 | NYC |
| 1 | LA |
| 2 | NYC |
| 3 | NaN |
Specifying the step touches no data:
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:
Recipe (trained)
Inputs: 1 columns (1 feature)
Steps:
step_unknown(city) [trained]
transform() recodes the nulls in place:
new_level names the added level: