Shrinkage-Adjusted Segment Lift Ranking
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Implement `shrunk_segment_lift(df, seg, metric, k)`. It groups rows by column `seg` and ranks the segments by a shrunk mean of column `metric`:
```text
shrunk_mean = (n * segment_mean + k * overall_mean) / (n + k)
```
`overall_mean` is the row-weighted mean of `metric` over all rows. It is not the average of the segment means. `k` is non-negative.
Return one row per segment with these columns, in this order:
- `segment` (object)
- `n` (int64), the number of non-null `metric` values in the segment, which is its row count when `metric` has no nulls
- `raw_mean`, `shrunk_mean` and `shrunk_lift` (float64), where `raw_mean` is the segment mean and `shrunk_lift = shrunk_mean - overall_mean`
- `raw_rank` and `shrunk_rank` (int64), where rank 1 goes to the segment with the highest `raw_mean` or `shrunk_mean` respectively
Each rank column holds the integers 1 to the number of segments, each used exactly once, so there are no gaps and no shared ranks. When two segments have the same mean, the one whose name sorts first gets the smaller rank. Sort the rows by `shrunk_rank` ascending and reset the index with `reset_index(drop=True)`.
```hint What the formula does
Rewrite `shrunk_mean - overall_mean` in terms of `raw_mean - overall_mean` and look at how the factor between them depends on `n` and `k`.
```
```hint Ranking with a tie-break
The built-in `rank` methods either give tied values the same rank or break ties by row position. Make the tie-break by segment name explicit, and apply it to both rank columns.
```
### Constraints & Assumptions
- `k` is non-negative. `k = 0` means no shrinkage.
- The result is compared with `assert_frame_equal`, so column order, dtypes, row order and the index all have to match.
### What a Strong Answer Covers
- The pooled mean over rows, and a per-segment count and mean from one grouped pass
- How `n` and `k` set the weight on a segment's own mean, and what that does to small and large segments
- Ranks that use each integer once, with the same name tie-break in both rank columns
- Exact column order, dtypes and final sort
- Behavior at the extremes: `k = 0`, very large `k`, and segments with very few rows
### Follow-up Questions
- How would you estimate `k` from the data?
- How does this extend to a hierarchy of segments, such as country, region and city?
- For a 0/1 conversion metric, how does this formula relate to a Beta prior?
Overview: Implement a pandas function that ranks segments by a shrunk mean, blending each segment's average with the pooled mean according to its size and a prior strength k. It tests grouped aggregation, ranking with an explicit tie-break, and the empirical Bayes reasoning that keeps tiny segments from topping a leaderboard.