Skip to main content

StepImputeMode

Impute missing values with the column mode (most frequent value).

Usage

Source

StepImputeMode(
    columns,
    *,
    id=None,
)

Each selected column has its nulls filled in place with that column’s mode.

Mode imputation is for categorical columns (it accepts Categorical/Enum/String, not numeric dtypes) and is dtype-preserving: the fill value is an observed level of the column. For numeric columns, see StepImputeMean or StepImputeMedian; to make missingness a level of its own, see StepUnknown.

A column that is entirely null at fit time has no mode; it is left unchanged (not dropped) with a warning, and passes through transform untouched.

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 impute. 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.

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

Examples

The null is filled in place with the column mode (the most frequent observed 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(StepImputeMode(s.nominal_features()))
recipe
Recipe (untrained)
  Inputs: no roles assigned
  Steps:
    step_impute_mode(select(role='feature', type=(String, Categorical, Enum)))  [untrained]

fit() finds the most frequent observed level:

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

transform() fills the nulls in place:

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