Rank segments by their size-weighted gap from the pooled mean in pandas

Quick Overview

Write a pandas function that ranks segments by how much each one pulls the pooled mean of a metric up or down, weighting each segment's lift by its row count. It tests groupby aggregation, the difference between rate and size-weighted impact, and an exact output schema and sort order.

Rank segments by their size-weighted gap from the pooled mean in pandas

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Write `segment_gap_contribution(df, seg, metric)` that ranks the segments of column `seg` by their total impact on the pooled mean of column `metric`. The pooled mean is the mean over all rows, not the mean of the segment means. Return a DataFrame with one row per segment. Requirements: - Columns, in this order: `segment` (object), `n` (int64), then `segment_mean`, `abs_lift`, `gap_contribution` and `abs_contribution_share_pct` (all float64). - `abs_lift = segment_mean - overall_mean`. "Absolute" here means a difference in the metric's own units as opposed to a relative lift, so the value keeps its sign. - `gap_contribution = abs_lift * n`. - `abs_contribution_share_pct = abs(gap_contribution) / sum_of_abs_gap_contributions * 100`. - Sort by `gap_contribution` ascending, then `segment` ascending, then `reset_index(drop=True)`. - The result is compared with `pd.testing.assert_frame_equal`, so the column order and dtypes must match exactly. Example: ```text df: region revenue A 10 A 20 B 25 A 10 B 30 C 10 A 20 B 35 segment_gap_contribution(df, "region", "revenue") segment n segment_mean abs_lift gap_contribution abs_contribution_share_pct 0 A 4 15.0 -5.0 -20.0 33.333333 1 C 1 10.0 -10.0 -10.0 16.666667 2 B 3 30.0 10.0 30.0 50.000000 ``` The pooled mean is 160 / 8 = 20. Segment C has the lowest mean, but it has one row, so A, with four rows at 5 below the mean, is the larger drag and comes first. ```hint A check on your numbers Add up `gap_contribution` over all segments in the example. Work out what that total should always be, and why. ``` ```hint Shape of the result `groupby` puts the segment labels in the index. Check the column order and every dtype of the frame you return. ``` ### Clarifying Questions to Ask - Can `metric` contain missing values, and if so, should `n` count all rows in the segment or only rows with a value? - Can `seg` contain missing values, and should those rows form their own segment? - What should `abs_contribution_share_pct` hold if every segment mean equals the overall mean, so all contributions are zero? - Can `seg` be a categorical column with categories that never occur in the data? ### What a Strong Answer Covers - Using the pooled row-level mean as the baseline, and why the mean of segment means is wrong for this purpose - Computing the per-segment count and mean in one grouped pass, then the signed lift and the size-weighted contribution - The share column, including the case where every contribution is zero - The two-key sort, the index reset, the column order and the exact dtypes - Why weighting by `n` can rank segments differently from ranking by segment mean ### Follow-up Questions - Why can ranking by `gap_contribution` mislead when segments overlap or are correlated? - How would you add a confidence signal so tiny segments are not over-trusted? - The overall mean dropped between two periods. How would you split the change into a part caused by segment means changing and a part caused by the segment mix changing?

Overview: Write a pandas function that ranks segments by how much each one pulls the pooled mean of a metric up or down, weighting each segment's lift by its row count. It tests groupby aggregation, the difference between rate and size-weighted impact, and an exact output schema and sort order.

General logo
General
Nov 25, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Write segment_gap_contribution(df, seg, metric) that ranks the segments of column seg by their total impact on the pooled mean of column metric. The pooled mean is the mean over all rows, not the mean of the segment means. Return a DataFrame with one row per segment.

Requirements:

  • Columns, in this order: segment (object), n (int64), then segment_mean , abs_lift , gap_contribution and abs_contribution_share_pct (all float64).
  • abs_lift = segment_mean - overall_mean . "Absolute" here means a difference in the metric's own units as opposed to a relative lift, so the value keeps its sign.
  • gap_contribution = abs_lift * n .
  • abs_contribution_share_pct = abs(gap_contribution) / sum_of_abs_gap_contributions * 100 .
  • Sort by gap_contribution ascending, then segment ascending, then reset_index(drop=True) .
  • The result is compared with pd.testing.assert_frame_equal , so the column order and dtypes must match exactly.

Example:

df:
  region  revenue
  A       10
  A       20
  B       25
  A       10
  B       30
  C       10
  A       20
  B       35

segment_gap_contribution(df, "region", "revenue")

  segment  n  segment_mean  abs_lift  gap_contribution  abs_contribution_share_pct
0       A  4          15.0      -5.0             -20.0                   33.333333
1       C  1          10.0     -10.0             -10.0                   16.666667
2       B  3          30.0      10.0              30.0                   50.000000

The pooled mean is 160 / 8 = 20. Segment C has the lowest mean, but it has one row, so A, with four rows at 5 below the mean, is the larger drag and comes first.

Clarifying Questions to Ask Guidance

  • Can metric contain missing values, and if so, should n count all rows in the segment or only rows with a value?
  • Can seg contain missing values, and should those rows form their own segment?
  • What should abs_contribution_share_pct hold if every segment mean equals the overall mean, so all contributions are zero?
  • Can seg be a categorical column with categories that never occur in the data?

What a Strong Answer Covers Guidance

  • Using the pooled row-level mean as the baseline, and why the mean of segment means is wrong for this purpose
  • Computing the per-segment count and mean in one grouped pass, then the signed lift and the size-weighted contribution
  • The share column, including the case where every contribution is zero
  • The two-key sort, the index reset, the column order and the exact dtypes
  • Why weighting by n can rank segments differently from ranking by segment mean

Follow-up Questions Guidance

  • Why can ranking by gap_contribution mislead when segments overlap or are correlated?
  • How would you add a confidence signal so tiny segments are not over-trusted?
  • The overall mean dropped between two periods. How would you split the change into a part caused by segment means changing and a part caused by the segment mix changing?