Segment Lift vs Overall Mean
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Write `segment_lift(df, seg, metric)`. `seg` names a segment column with string values and `metric` names a numeric column. Return a new DataFrame with one row per distinct segment that compares each segment's mean of `metric` with the pooled mean of the whole `metric` column. Do not add columns to `df` and return it.
The result must meet these requirements:
- Columns in this exact order and dtype: `segment` (object), `n` (int64, rows in the segment), `segment_mean`, `overall_mean`, `abs_lift`, `pct_lift` (all four float64), `direction` (object).
- `overall_mean` is the same pooled mean, repeated on every row.
- `abs_lift = segment_mean - overall_mean` and `pct_lift = abs_lift / overall_mean * 100`.
- `direction` is `'over'` if `abs_lift > 0`, `'under'` if `abs_lift < 0`, and `'at'` otherwise.
- Rows are sorted by `pct_lift` descending with ties broken by `segment` ascending, and the index is reset with `reset_index(drop=True)`.
```hint Benchmark and dtypes
The benchmark is one scalar taken from the full column, so compute it before you group. Before returning, compare each column's dtype with the spec, because `assert_frame_equal` checks dtypes as well as values.
```
### Constraints & Assumptions
- The function is graded with `assert_frame_equal` on a fixed frame of about 12 rows and 4 segments, so column order, dtypes, row order and the index all have to match.
- `metric` is numeric.
- Every row has a non-null segment.
### What a Strong Answer Covers
- How the pooled benchmark is computed, and why it differs from an average of the segment means when segments have different sizes
- A grouped aggregation that produces the row count and mean per segment
- The three-way `direction` label and the two-key sort with an index reset
- Exact column order and dtypes for the frame comparison
- What happens to `pct_lift` when the pooled mean is zero or negative
### Follow-up Questions
- How would you handle an `overall_mean` of 0?
- How does a negative pooled mean change the meaning of `pct_lift` and the sort order?
- How would you flag whether a segment's lift is statistically significant?
Overview: Write a pandas function that compares each segment's mean of a metric with the pooled mean of the whole column, reporting absolute lift, percent lift and a direction label in a fixed sort order. It tests grouped aggregation, exact column order and dtypes, and the edge cases of a zero or negative benchmark.