df = pd.DataFrame({"x": [1.0, 2.0, None, 4.0]})
df| x | |
|---|---|
| 0 | 1.0 |
| 1 | 2.0 |
| 2 | NaN |
| 3 | 4.0 |
Impute missing numeric values with the column median.
Usage
Each selected numeric column has its nulls filled in place with that column’s median, which is less sensitive to outliers than the mean (see StepImputeMean). Categorical columns need StepImputeMode. To keep a record of which values were missing, see StepIndicateNa.
A column that is entirely null at fit time has no median to impute with; 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.numeric_features() (see Selectors for the full set), or a narwhals or polars selector (narwhals.selectors.numeric(), polars.selectors.numeric()). Selectors are resolved against the data frame’s schema when the recipe is fitted, so the same selector works on any backend. Only numeric columns are meaningful here.
id: str | None = None"impute_median"; a second step of this type in the same recipe becomes "impute_median_2", and passing an id already used in the recipe is an error.
The null is filled in place with the column median of the observed values:
Specifying the step touches no data:
Recipe (untrained)
Inputs: no roles assigned
Steps:
step_impute_median(select(role='feature', type=NumericType)) [untrained]
fit() computes the median of the observed values:
Recipe (trained)
Inputs: 1 columns (1 feature)
Steps:
step_impute_median(x) [trained]
transform() fills the nulls in place: