df = pd.DataFrame(
{
"x": list(range(1000)),
"sparse": [1.0] + [0.0] * 999,
}
)
df| x | sparse | |
|---|---|---|
| 0 | 0 | 1.0 |
| 1 | 1 | 0.0 |
| 2 | 2 | 0.0 |
| 3 | 3 | 0.0 |
| 4 | 4 | 0.0 |
| ... | ... | ... |
| 995 | 995 | 0.0 |
| 996 | 996 | 0.0 |
| 997 | 997 | 0.0 |
| 998 | 998 | 0.0 |
| 999 | 999 | 0.0 |
1000 rows × 2 columns
Remove columns that are sparse and unbalanced (near-zero variance).
Usage
A selected column is dropped if it has a single unique value (or is entirely missing), or if it is both highly concentrated on one value and has few unique values relative to the number of samples: the ratio of the most common value’s count to the second most common value’s count exceeds freq_cut, and the percentage of unique values is at or below unique_cut. No new columns are produced. To drop only columns with a single unique value, see StepDropZeroVariance.
See Zero Variance Filter 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 consider for removal. Accepts a single column name, a list of names, a mlfeatures selector such as Selectors.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. Any dtype is accepted.
freq_cut: float = 95 / 5
Threshold for the frequency ratio of the most common value to the second most common value. Defaults to 95 / 5.
unique_cut: float = 10Threshold, in percent, for the share of unique values. Defaults to 10, and must be between 0 and 100.
id: str | None = None"nzv"; a second step of this type in the same recipe becomes "nzv_2", and passing an id already used in the recipe is an error.
sparse is a single value repeated 999 times with one outlier, so it is dropped; x is kept:
| x | sparse | |
|---|---|---|
| 0 | 0 | 1.0 |
| 1 | 1 | 0.0 |
| 2 | 2 | 0.0 |
| 3 | 3 | 0.0 |
| 4 | 4 | 0.0 |
| ... | ... | ... |
| 995 | 995 | 0.0 |
| 996 | 996 | 0.0 |
| 997 | 997 | 0.0 |
| 998 | 998 | 0.0 |
| 999 | 999 | 0.0 |
1000 rows × 2 columns
Specifying the step touches no data:
Recipe (untrained)
Inputs: no roles assigned
Steps:
step_drop_near_zero_variance(select(role='feature', type=NumericType)) [untrained]
fit() computes each column’s frequency ratio and percent of unique values:
Recipe (trained)
Inputs: 1 columns (1 feature)
Steps:
step_drop_near_zero_variance(x, sparse) [trained]
transform() drops the sparse, unbalanced one:
| x | |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| ... | ... |
| 995 | 995 |
| 996 | 996 |
| 997 | 997 |
| 998 | 998 |
| 999 | 999 |
1000 rows × 1 columns
A tighter unique_cut can keep columns that would otherwise be dropped: