Statistical modeling with Python · Lesson 6 of 16

Chi-square test and tests for proportions

Test whether two categories are linked with chi2_contingency, compare two conversion rates with a z-test, and test one share with binomtest.

About 15 minutes · code runs in your browser, nothing to install

t-tests compare averages of numbers. When the data are categories (bought / did not buy, mobile / desktop, yes / no), you compare counts and shares instead. This lesson covers the three tests you will use most.

Chi-square test of independence

A shop recorded, for 300 visitors, the device they used and whether they bought. Is buying linked to the device, or do all devices convert about the same? First the table of counts, a contingency table (pd.crosstab makes one from raw rows).

Pythoneditable
def show_p(p):
    return "p < 0.001" if p < 0.001 else f"p = {p:.3f}"

import pandas as pd
from scipy import stats

table = pd.DataFrame({"bought": [42, 38, 10], "no": [78, 62, 70]},
                     index=["desktop", "mobile", "tablet"])
print(table)
print((table["bought"] / table.sum(axis=1)).round(3))

res = stats.chi2_contingency(table)
print(f"chi2 = {res.statistic:.2f}, dof = {res.dof}, {show_p(res.pvalue)}")
Output
         bought  no
desktop      42  78
mobile       38  62
tablet       10  70
desktop    0.350
mobile     0.380
tablet     0.125
dtype: float64
chi2 = 16.14, dof = 2, p < 0.001

How to read it: the test compares the counts you saw with the counts you would expect if device and buying were unrelated. A big gap gives a big chi-square value and a small p-value. Here p is below 0.001: the rates are very unlikely to be equal on all devices. The test itself does not say which device differs; the shares do: desktop (35%) and mobile (38%) convert much better than tablet (12.5%).

Pythoneditable
import pandas as pd
from scipy import stats

table = pd.DataFrame({"bought": [42, 38, 10], "no": [78, 62, 70]},
                     index=["desktop", "mobile", "tablet"])
res = stats.chi2_contingency(table)
expected = pd.DataFrame(res.expected_freq, index=table.index, columns=table.columns)
print(expected.round(1))
Output
         bought    no
desktop    36.0  84.0
mobile     30.0  70.0
tablet     24.0  56.0

The expected counts if buying did not depend on the device.

Watch out: The chi-square test needs enough data: every expected count should be at least about 5. For small 2×2 tables use stats.fisher_exact(table) instead. For 2×2 tables chi2_contingency applies a small correction (Yates) by default.

Comparing two proportions: an A/B test

Page A converted 45 of 500 visitors (9.0%), page B 68 of 500 (13.6%). proportions_ztest from statsmodels tests whether the two rates differ. The z statistic plays the role of t.

Pythoneditable
def show_p(p):
    return "p < 0.001" if p < 0.001 else f"p = {p:.3f}"

from statsmodels.stats.proportion import proportions_ztest, confint_proportions_2indep

buyers = [68, 45]   # page B, page A
visitors = [500, 500]
z, p = proportions_ztest(buyers, visitors)
print(f"B: {buyers[0] / visitors[0]:.1%}, A: {buyers[1] / visitors[1]:.1%}")
print(f"z = {z:.2f}, {show_p(p)}")
low, high = confint_proportions_2indep(buyers[0], visitors[0], buyers[1], visitors[1])
print(f"95% CI of B - A: {low:.1%} to {high:.1%}")
Output
B: 13.6%, A: 9.0%
z = 2.30, p = 0.022
95% CI of B - A: 0.7% to 8.6%

p = 0.022: a gap this large would be unusual if both pages truly converted equally. The interval says B is better by somewhere between 0.7 and 8.6 percentage points: real, but the size is uncertain, so more data would pin it down.

One proportion: is the share different from a claim?

A supplier promises at most 5% faulty parts. In a box of 200 you find 17 faulty. binomtest asks: is 17 out of 200 surprising if the true rate is 5%? alternative="greater" because only more faults are bad news.

Pythoneditable
def show_p(p):
    return "p < 0.001" if p < 0.001 else f"p = {p:.3f}"

from scipy import stats

res = stats.binomtest(17, n=200, p=0.05, alternative="greater")
print(f"observed share: {17 / 200:.1%}")
print(f"{show_p(res.pvalue)}")
ci = res.proportion_ci(confidence_level=0.95)
print(f"one-sided 95% interval: from {ci.low:.1%}")
Output
observed share: 8.5%
p = 0.024
one-sided 95% interval: from 5.5%

✎ Exercise

A survey asked 150 people in each of two cities whether they cycle to work: 33 said yes in Ghent, 18 in Lille. Run proportions_ztest and print each city's share (1 decimal %) and the p-value with 3 decimals.

Hint: proportions_ztest([33, 18], [150, 150]) returns (z, p).

Your codewrite your answer, then Run
from statsmodels.stats.proportion import proportions_ztest

# your code here

Expected output:

Ghent: 22.0%, Lille: 12.0%
p = 0.021
Show a solution
Solutioneditable
from statsmodels.stats.proportion import proportions_ztest

yes = [33, 18]
asked = [150, 150]
z, p = proportions_ztest(yes, asked)
print(f"Ghent: {yes[0] / asked[0]:.1%}, Lille: {yes[1] / asked[1]:.1%}")
print(f"p = {p:.3f}")
Output
Ghent: 22.0%, Lille: 12.0%
p = 0.021

Check yourself

1. What does the chi-square test of independence compare?

2. A 2×2 table has an expected count of 2 in one cell. What should you use?

3. Page B converts better than A with p = 0.02. What else should you report?

Spotted a mistake on this page? Tell us