Cross-Column Level Lift Screening
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `top_lift_levels(df, cat_cols, target, min_n)`. For every level of every column in `cat_cols`, compute `n` (the row count), `target_rate` (the mean of the 0/1 `target`) and `lift = target_rate / overall_base_rate`, where the base rate is the mean of `target` over the whole frame.
Requirements:
- Exclude any level with `n < min_n`.
- Return exactly the columns `['feature', 'level', 'n', 'target_rate', 'lift']`, where `feature` is the column name.
- Cast `level` to `str` (object dtype).
- Sort by `lift` descending, then `feature` ascending, then `level` ascending, then call `reset_index(drop=True)`.
- If no level clears `min_n`, return an empty DataFrame with the same five columns and dtypes.
Example, where the base rate is 0.15 and the level `'A'` of `region` has `n = 120` and `target_rate = 0.30`, so its lift is 0.30 / 0.15 = 2.0:
```python
top_lift_levels(df, cat_cols=['region', 'plan'], target='y', min_n=50)
```
```text
feature level n target_rate lift
0 region A 120 0.30 2.0
1 plan pro 80 0.24 1.6
```
A level with a higher lift but only 12 rows does not appear, because `min_n = 50` removes it.
```hint Where each number comes from
The base rate is computed once over the whole frame. Per column, a single grouped aggregation can produce both the count and the rate.
```
```hint The strict comparison
The result is compared with `assert_frame_equal`. Check its dtypes and index in two awkward cases: no level clears `min_n`, and a column whose levels are integers or a categorical.
```
### Constraints & Assumptions
- `target` is a 0/1 column.
- Missing values in a `cat_cols` column do not form a level (the default `groupby` behavior), but those rows still count toward the base rate.
- Output dtypes are `object` for `feature` and `level`, `int64` for `n`, and `float64` for `target_rate` and `lift`.
### What a Strong Answer Covers
- Computes the base rate once over the full frame, and `n` and `target_rate` per level with one grouped aggregation per column.
- Applies the `min_n` filter, the three-key sort and `reset_index(drop=True)` as specified.
- Casts `level` to string and returns the exact columns and dtypes, including the empty result.
- Handles the edge cases: empty `cat_cols`, unused categorical levels, and a base rate of 0.
- Explains what a large lift on a small level means and how `min_n` trades noise against coverage.
### Follow-up Questions
- How would you extend this to flag only levels whose lift is statistically significant?
- How would you handle missing values (`NaN`) within a categorical column?
Overview: Implement a pandas function that screens every level of several categorical columns for lift in a binary target rate, with a minimum row count and a strict three-key sort. It tests grouped aggregation, exact output dtypes for the empty case, and judgment about small segments.