Compare Segments with Direct Standardization over a Confounder in pandas

Quick Overview

Write a pandas function that compares segments by direct standardization, reweighting each segment's per-stratum means by the overall confounder mix and flagging segments whose rank changes. It tests confounding adjustment, groupby and label alignment in pandas, and deterministic ranking with ties.

Compare Segments with Direct Standardization over a Confounder in pandas

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: medium

Interview Round: Other

Write `standardized_segment_comparison(df, seg, metric, confounder)` returning one row per segment. Compare segments by direct standardization: reweight each segment's per-stratum `metric` means using the overall population's distribution of `confounder`. Requirements: - Columns, in this order: `segment` (object), `n` (int64), `crude_mean` (float64), `standardized_mean` (float64), `adjustment` (float64), `rank_changed` (bool). - `crude_mean` is the plain mean of `metric` within the segment, and `adjustment = standardized_mean - crude_mean`. - `standardized_mean = sum_over_strata(overall_stratum_weight * segment_stratum_mean)`, where a stratum's weight is its share of all rows in `df`, so the weights sum to 1.0. - `rank_changed` is `True` when the segment's rank by `crude_mean` differs from its rank by `standardized_mean`. Both ranks are descending, with ties broken by `segment` ascending. - Sort by `standardized_mean` descending, ties by `segment` ascending, then `reset_index(drop=True)`. Example: ```python df = pd.DataFrame({ "region": ["A"] * 4 + ["B"] * 4 + ["C"] * 4, "tier": ["easy", "easy", "easy", "hard", "easy", "hard", "hard", "hard", "easy", "easy", "hard", "hard"], "spend": [8, 8, 8, 2, 9, 3, 3, 3, 4, 4, 2, 2], }) standardized_segment_comparison(df, "region", "spend", "tier") # segment n crude_mean standardized_mean adjustment rank_changed # 0 B 4 4.5 6.0 1.5 True # 1 A 4 6.5 5.0 -1.5 True # 2 C 4 3.0 3.0 0.0 False ``` Half of all rows are `easy` and half are `hard`, so each standardized mean is the average of the segment's two stratum means. A leads on the crude mean because three of its four rows sit in the easy stratum, and it falls behind B once both are scored on the same mix. ```hint One shared mix The weights come from the whole frame and are the same for every segment. Check that they line up with the stratum means by stratum label. ``` ```hint Ranking Compute both rankings with the same tie rule before the final sort, so `rank_changed` does not depend on row order. ``` ### Constraints & Assumptions - Every segment has at least one row in every stratum. - The result is graded with `assert_frame_equal`, so dtypes and column order must match exactly. ### What a Strong Answer Covers - Computing the stratum weights once from all rows and applying the same weights to every segment. - Why the crude mean differs: it weights the stratum means by the segment's own mix. - Aligning weights to stratum means by label, and producing the exact columns and dtypes. - Two rankings with the same descending, segment-ascending tie rule, compared per segment. - Edge cases such as missing values in `confounder` or `metric`, and near-ties from floating-point sums. ### Follow-up Questions - How would you handle segments missing rows in some strata? - How would you attach uncertainty to `standardized_mean`? - When would you use indirect standardization instead, and what does it cost you?

Overview: Write a pandas function that compares segments by direct standardization, reweighting each segment's per-stratum means by the overall confounder mix and flagging segments whose rank changes. It tests confounding adjustment, groupby and label alignment in pandas, and deterministic ranking with ties.

Nov 24, 2026
mediumData ScientistOtherData Manipulation (SQL/Python)
0
0

Write standardized_segment_comparison(df, seg, metric, confounder) returning one row per segment. Compare segments by direct standardization: reweight each segment's per-stratum metric means using the overall population's distribution of confounder.

Requirements:

  • Columns, in this order: segment (object), n (int64), crude_mean (float64), standardized_mean (float64), adjustment (float64), rank_changed (bool).
  • crude_mean is the plain mean of metric within the segment, and adjustment = standardized_mean - crude_mean .
  • standardized_mean = sum_over_strata(overall_stratum_weight * segment_stratum_mean) , where a stratum's weight is its share of all rows in df , so the weights sum to 1.0.
  • rank_changed is True when the segment's rank by crude_mean differs from its rank by standardized_mean . Both ranks are descending, with ties broken by segment ascending.
  • Sort by standardized_mean descending, ties by segment ascending, then reset_index(drop=True) .

Example:

df = pd.DataFrame({
    "region": ["A"] * 4 + ["B"] * 4 + ["C"] * 4,
    "tier":   ["easy", "easy", "easy", "hard",
               "easy", "hard", "hard", "hard",
               "easy", "easy", "hard", "hard"],
    "spend":  [8, 8, 8, 2,
               9, 3, 3, 3,
               4, 4, 2, 2],
})
standardized_segment_comparison(df, "region", "spend", "tier")
#   segment  n  crude_mean  standardized_mean  adjustment  rank_changed
# 0       B  4         4.5                6.0         1.5          True
# 1       A  4         6.5                5.0        -1.5          True
# 2       C  4         3.0                3.0         0.0         False

Half of all rows are easy and half are hard, so each standardized mean is the average of the segment's two stratum means. A leads on the crude mean because three of its four rows sit in the easy stratum, and it falls behind B once both are scored on the same mix.

Constraints & Assumptions

  • Every segment has at least one row in every stratum.
  • The result is graded with assert_frame_equal , so dtypes and column order must match exactly.

What a Strong Answer Covers Guidance

  • Computing the stratum weights once from all rows and applying the same weights to every segment.
  • Why the crude mean differs: it weights the stratum means by the segment's own mix.
  • Aligning weights to stratum means by label, and producing the exact columns and dtypes.
  • Two rankings with the same descending, segment-ascending tie rule, compared per segment.
  • Edge cases such as missing values in confounder or metric , and near-ties from floating-point sums.

Follow-up Questions Guidance

  • How would you handle segments missing rows in some strata?
  • How would you attach uncertainty to standardized_mean ?
  • When would you use indirect standardization instead, and what does it cost you?