A/B Test Segment Analysis in Python: Heterogeneous Effects Without Fooling Yourself

Break an A/B test down by segment in Python, test whether the lift really differs across segments with an interaction test, and avoid the winner's curse with Holm correction and shrinkage.

Splitting an A/B test by segment (country, device, plan) often turns up a segment where the treatment "really works", and often that segment is noise. The safe order is: first test whether the lift differs across segments at all with an interaction test (compare treat * C(segment) against treat + C(segment) in statsmodels), then correct per-segment p-values with Holm, and treat the best-looking segment's lift as an overestimate. This post shows each step on a simulated test with 12 country segments.

Quick Example

Each of 12 countries has 4,000 users per arm. The baseline conversion rate is 10%. The treatment adds 1.0 percentage point (pp) everywhere except Brazil, where it adds 3.0 pp. The code computes each segment's lift, its raw and Holm-adjusted p-values, and a likelihood-ratio test for the interaction.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats
from statsmodels.stats.multitest import multipletests

rng = np.random.default_rng(12)

# Sample data: 12 country segments, 4,000 users per arm each
segments = ["US", "UK", "Germany", "France", "Spain", "Italy", "Canada", "Brazil", "Mexico", "India", "Japan", "Australia"]
true_lift = {s: 0.010 for s in segments}
true_lift["Brazil"] = 0.030
base, n_arm = 0.10, 4000
rows = []
for s in segments:
    for treat in (0, 1):
        p = base + treat * true_lift[s]
        rows.append(pd.DataFrame({"segment": s, "treat": treat, "converted": rng.binomial(1, p, n_arm)}))
users = pd.concat(rows, ignore_index=True)

# Per-segment lift, standard error, p-value (z-test), Holm-adjusted p-value
g = users.groupby(["segment", "treat"]).converted.agg(["sum", "count"]).unstack()
res = pd.DataFrame(index=segments)
res["rate_c"] = g[("sum", 0)] / g[("count", 0)]
res["rate_t"] = g[("sum", 1)] / g[("count", 1)]
res["lift"] = res.rate_t - res.rate_c
res["se"] = np.sqrt(res.rate_c * (1 - res.rate_c) / g[("count", 0)] + res.rate_t * (1 - res.rate_t) / g[("count", 1)])
res["p"] = 2 * stats.norm.sf(np.abs(res.lift / res.se))
res["p_holm"] = multipletests(res.p, method="holm")[1]
overall = users.groupby("treat").converted.mean()
print("overall lift:", round(overall[1] - overall[0], 4))
print(res[["lift", "se", "p", "p_holm"]].round(4).to_string())

# Interaction test: does the lift differ across segments at all?
m0 = smf.logit("converted ~ treat + C(segment)", users).fit(disp=0)
m1 = smf.logit("converted ~ treat * C(segment)", users).fit(disp=0)
lr = 2 * (m1.llf - m0.llf)
df_diff = m1.df_model - m0.df_model
print(f"interaction LR test: chi2={lr:.2f}, df={df_diff:.0f}, p={stats.chi2.sf(lr, df_diff):.3f}")

order = res.sort_values("lift").index
fig, ax = plt.subplots(figsize=(8.5, 5.2))
for i, s in enumerate(order):
    r = res.loc[s]
    color = "#d1495b" if r.p < 0.05 else "#8a8f98"
    ax.errorbar(r.lift * 100, i, xerr=1.96 * r.se * 100, fmt="o", color=color, ecolor=color, capsize=3, ms=6)
ax.axvline(0, color="black", lw=0.8)
ax.axvline((overall[1] - overall[0]) * 100, color="#1b6ca8", ls="--", lw=1.5, label="Overall lift")
ax.set_yticks(np.arange(len(order)))
ax.set_yticklabels(order)
ax.set_xlabel("Conversion lift (percentage points), 95% CI")
ax.set_title("Red: p < 0.05 before correction")
ax.legend(loc="lower right")
fig.tight_layout()

Dot plot of conversion lift with 95 percent intervals for 12 countries, sorted. Brazil, Italy and the US are highlighted in red as significant before correction. Intervals for all countries are wide and overlap each other and the overall lift line at 1.0 point

The overall lift is 1.00 pp. Three countries are significant at 0.05 before correction: Brazil (2.30 pp), Italy (2.02) and the US (1.90). Only Brazil has a real bigger effect. After Holm correction Brazil (adjusted p 0.013) and Italy (0.037) are still below 0.05, so Italy is a false positive that survived the correction, and the US drops out (0.057). That happens: 5% error control per test is a rate, not a guarantee. The interaction test, which asks whether the lift varies by country at all, gives p = 0.171, so it does not flag any difference. That is right about Italy and the US, and it also misses Brazil's real extra effect, which shows how little power it has here.

How Do I Test Whether a Treatment Effect Differs by Segment?

The interaction test asks one question about all segments together, which avoids 12 separate chances at a false positive. Fit two models: one where the treatment effect is the same everywhere (treat + C(segment)) and one where each segment gets its own effect (treat * C(segment)). A likelihood-ratio test compares them. Here chi-square is 15.26 on 11 degrees of freedom, p = 0.171.

For a conversion metric that is a logistic regression, as in the code above. For a continuous metric, use smf.ols with the same formulas and compare them with anova_lm. If the interaction test is not significant, report one overall effect and call segment differences exploratory.

A real 2 pp gap in one segment out of 12, with 4,000 users per arm, is hard to detect: each segment's standard error is about 0.67 pp, so the interaction test has low power. A non-significant result means "no evidence", not "no differences". Plan segment analyses in advance and size the test for them.

Why Does the Best Segment Overstate the Lift?

If you pick the segment with the highest observed lift, you are picking in part for good luck. To see how large that is, simulate the same experiment 5,000 times with no real differences (1.0 pp in every segment) and record the best segment each time:

rs = np.random.default_rng(99)
SIMS, K = 5000, len(segments)
best_lift = []
for _ in range(SIMS):
    c = rs.binomial(n_arm, base, K) / n_arm
    t = rs.binomial(n_arm, base + 0.010, K) / n_arm
    best_lift.append((t - c).max() * 100)
best_lift = np.array(best_lift)
print("average best-segment lift (pp):", round(best_lift.mean(), 2))
print("share of experiments where the best segment shows 2 pp or more:", round(np.mean(best_lift >= 2), 3))

fig, ax = plt.subplots(figsize=(8, 4.4))
ax.hist(best_lift, bins=40, color="#e9a23b", edgecolor="white")
ax.axvline(1.0, color="#1b6ca8", lw=2, ls="--", label="True lift in every segment: 1.0 pp")
ax.axvline(best_lift.mean(), color="#d1495b", lw=2, label=f"Average best segment: {best_lift.mean():.2f} pp")
ax.set_xlabel("Lift of the best-looking segment (percentage points)")
ax.set_ylabel("Simulated experiments")
ax.legend()
fig.tight_layout()

Histogram of the best-looking segment's lift across 5,000 simulated experiments in which every segment has a true lift of 1 point. The distribution is centered near 2.1 points, far to the right of the dashed line at 1.0

The best of 12 identical segments averaged 2.11 pp, more than double the true 1.0 pp, and in 59% of experiments it showed 2 pp or more. This is the winner's curse: the selected estimate is biased upward. Brazil's 2.30 pp (true effect 3.0) and Italy's 2.02 pp (true effect 1.0) look alike in the data, although one is a real outlier and the other is luck.

How Do I Get More Honest Segment Estimates?

Shrinkage (partial pooling) pulls each segment's estimate toward the overall mean, more strongly the noisier it is. A simple empirical-Bayes version for normal estimates:

  1. Estimate the overall mean mu as a precision-weighted average.
  2. Estimate the true between-segment variance tau^2 from the excess of Cochran's Q over its degrees of freedom (method of moments).
  3. Shrink each estimate: shrunk = B * mu + (1 - B) * lift, where B = se^2 / (se^2 + tau^2).
K = len(res)
w = 1 / res.se ** 2
mu = np.sum(w * res.lift) / np.sum(w)
Q = np.sum(w * (res.lift - mu) ** 2)
tau2 = max(0.0, (Q - (K - 1)) / (np.sum(w) - np.sum(w ** 2) / np.sum(w)))
B = res.se ** 2 / (res.se ** 2 + tau2)
res["shrunk"] = B * mu + (1 - B) * res.lift
print(f"mu {mu * 100:.2f} pp, tau {np.sqrt(tau2) * 100:.2f} pp, Q {Q:.1f} on {K - 1} df")
print((res[["lift", "shrunk"]] * 100).round(2).T.to_string())

fig, ax = plt.subplots(figsize=(8.5, 5.2))
order = res.sort_values("lift").index
for i, s in enumerate(order):
    ax.plot([res.lift[s] * 100, res.shrunk[s] * 100], [i, i], color="#b0b6bf", lw=1.5, zorder=1)
ax.scatter(res.lift[order] * 100, range(K), color="#e76f51", s=40, label="Raw segment lift", zorder=2)
ax.scatter(res.shrunk[order] * 100, range(K), color="#1b6ca8", s=40, label="Shrunk toward overall mean", zorder=3)
ax.set_yticks(range(K))
ax.set_yticklabels(order)
ax.axvline(0, color="black", lw=0.8)
ax.set_xlabel("Conversion lift (percentage points)")
ax.legend(loc="lower right")
fig.tight_layout()

Dumbbell chart for 12 countries connecting each raw lift estimate to its shrunk estimate. Extreme values such as Brazil at 2.3 points and Japan at minus 0.4 points move toward the overall mean of about 1 point

The estimated between-segment standard deviation is 0.44 pp, so the method concludes most of the spread is noise and shrinks heavily. Brazil goes from 2.30 pp to 1.36 pp, Italy from 2.02 to 1.29, and Japan from -0.38 to 0.58. This is the price: Brazil's true effect of 3.0 pp is shrunk further from the truth, because with this much noise the data cannot distinguish a real outlier from a lucky one. Shrinkage is more accurate on average across segments, not for each individual segment. More users per segment, or a segment you chose before launch, reduces the problem.

What Should I Do With Segment Results?

Situation What to do
Interaction test not significant Report the overall effect. Show segments as exploratory, with intervals
Few segments, chosen before launch Test each, with Holm correction or another multiple testing correction
Many segments, discovered after the fact Treat as hypotheses and confirm with a follow-up test on that segment
You need a number per segment Report shrunk estimates alongside raw ones
Segment is large and the effect plausible It may be worth acting on, but state the uncertainty

Practical Tips

  • Decide your segments before looking at results, and write them down. Adding cuts until something works is the source of most false segment findings.
  • Show intervals, not just point estimates. At 4,000 users per arm, every segment's interval here is about ±1.3 pp.
  • Segments of unequal size need unequal treatment: small segments get shrunk more.
  • Do not segment on anything affected by the treatment (for example, "users who saw the new checkout"), since that breaks the randomization.
  • The p-values and estimates here come from one seeded draw, so another seed would flag different countries. The winner's curse simulation is the stable result.

Similar Topics