🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Two-Proportion Z-Test — Comparing Two Proportions

Hypothesis TestingParametric Tests🟢 Free Lesson

Two-Proportion Z-Test

Hypothesis Testing

Comparing Rates Across Groups

The two-proportion z-test evaluates whether two groups have different success rates, forming the statistical backbone of A/B testing. It provides a rigorous framework for comparing binary outcomes.

  • Digital Marketing — Testing whether landing page designs produce different conversion rates
  • Medicine — Comparing treatment success rates in randomized clinical trials
  • Social Policy — Evaluating whether interventions reduce rates in different populations

The two-proportion test turns business questions into statistical evidence.


What You'll Learn

  • 1State the null and alternative hypotheses for a difference in two proportions
  • 2Explain why the test statistic uses a pooled standard error while the confidence interval does not
  • 3Compute the statistic by hand from a 2 by 2 table and read the result
  • 4Size an experiment for a target power and calculate relative risk, odds ratio and number needed to treat

Tests whether two population proportions are equal: H₀: π₁ = π₂. The outcome must be binary — converted or not, recovered or not, clicked or not — and each observation must contribute to exactly one group.

where is the pooled proportion.

Why Pooling Appears in One Place Only

Under the null hypothesis the two groups share a single true proportion, so the best estimate of that common value merges both samples. The pooled proportion is what the sampling distribution of the difference looks like when the difference really is zero, which is precisely the distribution the p-value must reference.

The confidence interval is a different question. It estimates the size of the difference without assuming it is zero, so pooling would drag the interval toward the null. Instead the interval uses the two separate sample proportions:

Getting this backwards is the most common error in proportion testing: a pooled standard error in the interval shrinks it when a difference exists, and an unpooled standard error in the test inflates the p-value when the difference is zero.

Conditions Before You Compute Anything

  1. Randomisation or a random sample. In an experiment this comes from random assignment; in a survey it comes from the sampling design. Without it the test estimates nothing about a population.
  2. Independence. Each unit appears once, in one group. Two conversions from the same user, or two sites from the same household, are not independent evidence.
  3. Enough successes and failures. The normal approximation to the binomial needs , , and each to be at least 10. The older rule of 5 is more permissive and visibly optimistic for rare events.
  4. Sample fraction below 10 percent. Sampling without replacement from a small population breaks the binomial variance assumption; the finite population correction then applies.

When the expected counts fall short, the alternatives are Fisher's exact test for small samples, a score or Wilson-based interval for a single proportion, or a logistic regression for adjusted comparisons.

A Worked Example From a Live A/B Test

An original landing page (A) converted 520 of 8,000 visitors; a redesign (B) converted 612 of 8,000.

Step 1 — the sample proportions.

The observed difference is 0.0115, or 1.15 percentage points in favour of B.

Step 2 — the pooled proportion.

Step 3 — the standard error and the statistic.

Step 4 — the p-value and the interval. The two-sided p-value is , so the null of equal conversion rates is rejected at 0.05 and at 0.01. The unpooled 95 percent interval for the difference runs from 0.0036 to 0.0194, entirely above zero, so a lift between 0.36 and 1.94 percentage points remains compatible with the data.

Step 5 — is it worth shipping? A 1.15 point lift on 8,000 visits is 92 extra conversions per 8,000. Whether that justifies the change depends on revenue per conversion, not on the p-value. Squaring the statistic gives the same answer as a chi-square test of independence: with 1 degree of freedom, .

Power and Sample Size

Because the effect of interest is a difference of proportions, power calculations need an assumed baseline and a minimum detectable effect:

Suppose the baseline conversion rate is 6.5 percent and you want 80 percent power to detect a rise to 7.65 percent at two-sided. With and :

Roughly 7,800 visitors per arm are required. Two observations follow. First, detecting a one-point absolute change on a six percent baseline costs thousands of units per group, which is why product experiments run for weeks. Second, halving the detectable effect quadruples the required sample, so the smallest effect worth acting on should be chosen before the numbers are collected.

Effect Size Measures for Proportions

A significant difference still needs a magnitude. Three measures answer three different questions.

MeasureFormulaWorked valueQuestion answered
Absolute risk difference0.0115How many extra conversions per visitor?
Number needed to treat87How many visitors per extra conversion?
Relative risk1.177How many times more likely is B?
Odds ratio1.192How do the odds compare?

Relative risk carries a log-scale standard error of , which for this example is 0.0575 and gives a 95 percent interval of 1.051 to 1.317 for the risk ratio. The odds ratio, 1.192 with an interval of 1.056 to 1.345, is the measure logistic regression reports and the natural one for case-control designs. When outcomes are common, the odds ratio drifts away from the relative risk and must not be described as a risk ratio.

Computing the Test in Python and R

python
import numpy as np
from scipy import stats

def two_prop_z_test(x1, n1, x2, n2, alternative='two-sided', alpha=0.05):
    p1, p2 = x1/n1, x2/n2
    p_pool = (x1 + x2) / (n1 + n2)

    expected = min(n1*p_pool, n1*(1-p_pool), n2*p_pool, n2*(1-p_pool))
    if expected < 10:
        print(f"WARNING: smallest expected count {expected:.1f} - use Fisher's exact test")

    se = np.sqrt(p_pool * (1 - p_pool) * (1/n1 + 1/n2))
    z = (p1 - p2) / se

    if alternative == 'two-sided':
        p_val = 2 * stats.norm.sf(abs(z))
    elif alternative == 'greater':
        p_val = stats.norm.sf(z)
    else:
        p_val = stats.norm.cdf(z)

    z_crit = stats.norm.ppf(1 - alpha/2)                 # unpooled SE for the CI
    se_ci = np.sqrt(p1*(1-p1)/n1 + p2*(1-p2)/n2)
    ci = (p1-p2 - z_crit*se_ci, p1-p2 + z_crit*se_ci)

    print(f"p1 = {x1}/{n1} = {p1:.4f}, p2 = {x2}/{n2} = {p2:.4f}")
    print(f"pooled p = {p_pool:.4f}, z = {z:.4f}, p-value = {p_val:.6f}")
    print(f"95% CI for p1-p2: ({ci[0]:.4f}, {ci[1]:.4f})")
    print(f"Decision: {'Reject H0' if p_val < alpha else 'Fail to reject H0'}")
    return z, p_val

two_prop_z_test(x1=520, n1=8000, x2=612, n2=8000)

# Sample size for 80% power to see 6.50% vs 7.65%
p1, p2, alpha, power = 0.065, 0.0765, 0.05, 0.80
pbar = (p1 + p2) / 2
za = stats.norm.ppf(1 - alpha/2)
zb = stats.norm.ppf(power)
n = ((za*np.sqrt(2*pbar*(1-pbar)) + zb*np.sqrt(p1*(1-p1)+p2*(1-p2)))**2) / (p1-p2)**2
print(f"required n per arm: {np.ceil(n):.0f}")

# Two-sided Fisher exact test as a small-sample fallback
print("Fisher p:", stats.fisher_exact([[520, 7480], [612, 7388]])[1])
# The same analysis in base R
a <- c(success = 520, failure = 8000 - 520)
b <- c(success = 612, failure = 8000 - 612)
tab <- rbind(A = a, B = b)

prop.test(tab, correct = FALSE)      # score test, equivalent to the pooled z-test
binom.test(520, 8000)$conf.int        # Wilson-style interval for one proportion

# Effect sizes with intervals
library(epitab)
riskratio(tab)                        # relative risk
oddsratio(tab)                        # odds ratio

# Power for a two-sided test at 80% power
power.prop.test(p1 = 0.065, p2 = 0.0765, power = 0.80, sig.level = 0.05)

💡The z-test and the chi-square test are the same test

Squaring a two-proportion z statistic gives the chi-square statistic on 1 degree of freedom, so the p-values match exactly for a two-sided comparison. Use whichever expresses your question more naturally, but do not report both as if they were independent evidence.

Practical Pitfalls in Experiment Platforms

  • Peeking without correction. Checking the p-value daily and stopping when it crosses 0.05 can push the real false positive rate past 20 percent. Fix the sample size in advance, or use a sequential design with alpha-spending boundaries.
  • Multiple variants and shared control. Testing four variants against one control at 0.05 each inflates the family-wise error rate. Apply a Holm or Bonferroni adjustment across the comparisons you actually care about.
  • Ratio metrics. Average revenue per user is not a proportion; the two-proportion test does not apply. Use a t-test on per-user values or a bootstrap for revenue ratios.
  • Interference and novelty effects. Peers influence each other and first-time reactions fade, both of which violate the independence and stationarity the test assumes. Run long enough for novelty to decay and check for network effects.

Common Mistakes

Using a pooled standard error in the confidence interval

Fix: Pool only inside the test statistic. The interval uses the two unpooled sample proportions so it does not assume the difference is zero.

Running the test when expected counts are tiny

Fix: Require 10 successes and 10 failures per group; below that use Fisher's exact test or a score interval.

Describing an odds ratio as a risk ratio

Fix: They coincide only for rare outcomes. Report the odds ratio as an odds ratio, or compute the relative risk directly.

Stopping the test as soon as p drops below 0.05

Fix: Pre-compute the sample size from the minimum detectable effect, or use a group-sequential plan with pre-set interim boundaries.

Best Practices

  • Report both proportions, the absolute difference with its interval, and a relative measure
  • Compute the required sample size before launch from a pre-declared minimum detectable effect
  • Check the four expected counts before trusting the normal approximation
  • Separate the statistical decision from the business decision; report the lift in business units as well as in percentage points

Key Takeaways

  • The test statistic uses the pooled proportion because the null hypothesis asserts one common true rate
  • The confidence interval uses unpooled standard errors because it does not assume the difference is zero
  • With 520 of 8,000 against 612 of 8,000 the result is z = 2.84, p = 0.0046, difference 1.15 points, interval 0.36 to 1.94 points
  • Detecting a 1.15 point change from a 6.5 percent baseline needs about 7,800 visitors per arm at 80 percent power
  • Relative risk, odds ratio and number needed to treat describe magnitude from three different angles

Interview Questions

Q1: Why is the proportion pooled under the null but not for the interval?

Under H0 both groups share one true proportion, so the pooled estimate gives the correct reference distribution for the p-value. The interval estimates an unknown difference without assuming it is zero, so it must use the two separate sample proportions.

Q2: How is the two-proportion z-test related to the chi-square test?

Squaring the z statistic yields the chi-square statistic with 1 degree of freedom, so the two-sided p-values are identical. They are the same test expressed in different scales.

Q3: When would you use Fisher's exact test instead?

When the expected cell counts drop below about 10, particularly with rare events or small samples. The normal approximation then misstates the tail probability, while Fisher's test computes the exact hypergeometric probability.

Q4: What is the most common design mistake in A/B testing?

Peeking at an uncorrected p-value and stopping early. Repeated significance checks inflate the false positive rate far above the nominal 5 percent unless the sample size is fixed in advance or a sequential testing plan is used.

Frequently Asked Questions

Should I use a continuity correction?

Software sometimes reports both a plain and a Yates-corrected chi-square. The correction is conservative and rarely changes a conclusion with more than about 50 observations per group, but it can matter for small samples. State which version you used, and prefer Fisher's exact test when counts are genuinely sparse rather than switching to Yates.

What if my groups have very different sizes?

The formulas handle unequal n without modification, since carries both. Power, however, is driven largely by the smaller group, so heavily unbalanced designs waste observations; near-equal allocation minimises the total sample size for a fixed power.

Can I compare more than two proportions this way?

Pairwise z-tests on three or more groups require a multiple comparison adjustment. For a global question — do any of these rates differ? — use a chi-square test of independence on the full contingency table first, then follow up with adjusted pairwise comparisons.

How do I compare proportions while adjusting for covariates?

Logistic regression. It estimates odds ratios conditional on the covariates, supplies a global test, and extends to continuous and multi-level predictors. The unadjusted two-proportion z-test remains the right starting point for a randomised comparison with one binary factor.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Statistics Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement