Mean vs Median Divergence by Segment
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
Write `segment_mean_median_divergence(df, seg, metric, threshold_pct)` that groups `df` by `seg`, measures how far each segment's mean of `metric` drifts from its median, and flags segments where the mean is misleading.
Requirements:
- One row per segment, columns: `segment` (object), `n` (int64), `segment_mean`, `segment_median`, `gap_pct` (float64), `mean_misleading` (bool).
- `n` is the number of non-null `metric` values in the segment.
- `gap_pct = (segment_mean - segment_median) / segment_median * 100`.
- `mean_misleading` is `True` when `abs(gap_pct) > threshold_pct`.
- Sort by `gap_pct` descending, then `segment` ascending, then `reset_index(drop=True)`.
```hint Aggregate once
`groupby(...).agg(...)` with named aggregations returns the count, mean and median per segment in one pass and names the output columns for you.
```
```hint Exact frame match
`assert_frame_equal` compares column order, dtypes and the index. Check the dtype of each column after the groupby, and what the index looks like after sorting.
```
### Constraints & Assumptions
- `df` has a segment column named by `seg` and a numeric column named by `metric`.
- The grader calls the function with `threshold_pct=10.0` and compares the result with `pandas.testing.assert_frame_equal`, so column names, column order and dtypes must match exactly.
### What a Strong Answer Covers
- A single grouped aggregation that yields the count, mean and median per segment, with the group key returned as a column named `segment`.
- The gap formula and a boolean flag on the absolute gap compared with `threshold_pct`.
- The column order, dtypes, two-key sort and reset index that an exact frame comparison requires.
- What missing `metric` values and a zero or negative median do to `n`, `gap_pct` and the flag.
- Why a large positive gap points to right skew from a few very large values.
### Follow-up Questions
- How would you make the skew flag less fragile than a raw mean/median gap, for example when the median is close to zero?
- What happens when a segment's median is 0 or negative?
- Revenue per user is heavily skewed, yet finance teams still report the mean. When is the mean the right summary even though this function flags it?
Overview: Write a pandas function that groups a DataFrame by segment, compares each segment's mean and median, and flags segments where skew makes the mean misleading. It tests groupby aggregation, exact output dtypes and sort order, and how a zero or negative median breaks a percentage gap.