df = pd.DataFrame(
{"city": pd.Series(["NYC", "LA", "NYC", None], dtype="category")}
)
df| city | |
|---|---|
| 0 | NYC |
| 1 | LA |
| 2 | NYC |
| 3 | NaN |
Impute missing values with the column mode (most frequent value).
Usage
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.
columns: SelectorColumns 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"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.
The null is filled in place with the column mode (the most frequent observed level):
| city | |
|---|---|
| 0 | NYC |
| 1 | LA |
| 2 | NYC |
| 3 | NaN |
Specifying the step touches no data:
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:
Recipe (trained)
Inputs: 1 columns (1 feature)
Steps:
step_impute_mode(city) [trained]
transform() fills the nulls in place: