Near-zero-variance feature screen with frequency ratio and percent unique
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `near_zero_variance_report(df, freq_cut=19.0, unique_cut=10.0)`. For every column, compute a frequency ratio and a uniqueness percentage, then flag near-zero-variance columns with the dual criterion used by R's caret package.
The report must follow these rules:
- `freq_ratio` is the count of the most common value divided by the count of the second most common value, or numpy `inf` if the column has only one distinct value. `pct_unique` is `100 * nunique / len(df)`.
- `zero_var` is `True` when the column has at most 1 distinct value.
- `nzv` is `zero_var OR (freq_ratio > freq_cut AND pct_unique < unique_cut)`, with strict comparisons.
- The columns are exactly `['feature', 'freq_ratio', 'pct_unique', 'zero_var', 'nzv']`, with `feature` as object, `freq_ratio` and `pct_unique` as `float64`, and `zero_var` and `nzv` as bool.
- Rows follow the original `df.columns` order (unsorted), with `reset_index(drop=True)`.
For example, with 1,000 rows:
```python
n = 1000
df = pd.DataFrame({
"const_col": [7] * n,
"lop_col": [0] * 999 + [1],
"bal_col": ["a", "b"] * 500,
"spend_col": [0.0] * 800 + [float(i) for i in range(1, 201)],
})
near_zero_variance_report(df)
```
```text
feature freq_ratio pct_unique zero_var nzv
0 const_col inf 0.1 True True
1 lop_col 999.0 0.2 False True
2 bal_col 1.0 0.2 False False
3 spend_col 800.0 20.1 False False
```
The constant column is zero-variance. The 999-vs-1 column is dominated by one value and has almost no distinct values, so it is flagged. The balanced column and the spend column (800 zeros plus 200 different amounts) are kept.
```hint Top two counts
Get the counts in descending order so the two largest are easy to read off, and decide what happens before the division when a column has one distinct value or none.
```
```hint Test both criteria
Work through `spend_col` and `bal_col` by hand. Each one fails a different half of the rule, and seeing which half helps you get the boolean logic right.
```
### Constraints & Assumptions
- Every column is screened, whatever its dtype (numeric, string or categorical).
- Missing values are left out of the counts and the distinct count, as `value_counts()` and `nunique()` do by default, while `len(df)` still counts every row.
- The defaults are `freq_cut=19.0` (a 95/5 split) and `unique_cut=10.0` percent.
### What a Strong Answer Covers
- A frequency ratio built from the two largest counts, with the single-value case and ties handled.
- The uniqueness percentage over all rows, and the zero-variance flag.
- The combined rule with strict comparisons and the cutoffs taken from the arguments.
- Output columns, dtypes and row order exactly as specified.
- An explicit choice about missing values and its effect on the flags.
### Follow-up Questions
- How would you handle NaNs in the value counts?
- Why use the dual criterion instead of the frequency ratio alone?
- How would you use this screen in a modeling pipeline without letting the test set influence which features are dropped?
Overview: Implement a pandas report that computes each column's frequency ratio and percentage of unique values, then flags zero-variance and near-zero-variance features with a two-part cutoff rule. It tests value counts, edge cases for constant and all-missing columns, and exact output dtypes and order.