Segment Share of Total
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Implement `segment_share_of_total(df, seg, metric)`. It sums `metric` by `seg` and returns one row per segment with that segment's share of the grand total and a running cumulative share.
The result must meet these requirements:
- Columns in this exact order: `segment` (object), `metric_total` (float64, the segment sum), `share_pct` (float64, `metric_total / grand_total * 100`), `cumulative_share_pct` (float64).
- Rows are sorted by `metric_total` descending with ties broken by `segment` ascending, and the index is reset with `reset_index(drop=True)`.
- `cumulative_share_pct` is the running sum of `share_pct`, computed after sorting. Its final value must equal 100.0.
```hint Order of operations
One of the output columns depends on row order. Work out which steps have to happen before the sort and which only make sense after it.
```
### Constraints & Assumptions
- `grand_total` is the sum of `metric` over all rows. Assume it is non-zero.
- The function is graded with `assert_frame_equal` on a fixed frame of about 14 rows over 5 segments, so column order, dtypes, row order and the index all have to match.
### What a Strong Answer Covers
- Aggregating the metric per segment and computing the grand total the way the spec defines it
- When the running share is computed relative to the sort, and why that order matters
- Tie-breaking, the index reset, exact column order and float64 dtypes
- Why the last cumulative value reaches 100, and the inputs that would stop it from doing so
### Follow-up Questions
- How would you flag the smallest set of segments covering 80% of the total?
- How would you handle a `grand_total` of 0?
- What changes in this report if `metric` can be negative, such as net revenue after refunds?
Overview: Write a pandas function that sums a metric by segment and reports each segment's share of the grand total plus a running cumulative share in a fixed sort order. It tests grouped aggregation, why a running sum has to follow the final sort, tie-breaking, and Pareto-style follow-ups such as finding the segments that cover 80% of the total.