Chi-Square Test of Independence
Nonparametric Tests
Does knowing one category tell you another?
The test of independence starts from a table of counts: rows for the categories of one variable, columns for the categories of another, and a number in every cell. The question is whether the column proportions are the same across rows. If customer churn looks identical for every support tier, the variables are independent in the sense that matters operationally — the tier tells you nothing about churn, and segmenting by it buys you nothing.
This is the test most people mean when they say "chi-square", and it is the natural first tool whenever both variables are categorical. It shares its arithmetic with the goodness-of-fit test, but the expected counts are computed differently: instead of comparing against a distribution you stated in advance, you compare against the distribution implied by the marginal totals of the table itself.
- Both variables categorical; measured as counts in a contingency table.
- Tests whether row and column proportions differ across the table.
- Pairs with Cramér's V to express how large the association is.
Building the contingency table
A contingency table is a cross-tabulation of two categorical variables. The margins — the row and column totals — are not decorative: they are the quantities from which expected counts are derived, and they fully determine what "independent" would look like for this particular sample.
The logic of that formula is worth stating in words. If the variables are unrelated, the proportion of the grand total appearing in column j should be the same in every row, so row i receives its own row total multiplied by that common column proportion. Every expected count is therefore a statement about what the cell would contain if knowing the row gave you no information about the column.
import numpy as np
import pandas as pd
from scipy import stats
# Support tier vs churn, as observed counts
table = pd.DataFrame(
[[120, 80], # basic
[95, 55], # standard
[60, 15]], # premium
index=["basic", "standard", "premium"],
columns=["retained", "churned"],
)
row_totals = table.sum(axis=1)
col_totals = table.sum(axis=0)
grand_total = table.to_numpy().sum()
expected = np.outer(row_totals, col_totals) / grand_total
expected_df = pd.DataFrame(
expected, index=table.index, columns=table.columns
)
print("Observed:")
print(table)
print("\nExpected under independence:")
print(expected_df.round(2))
# The statistic, cell by cell
contributions = (table.to_numpy() - expected) ** 2 / expected
print("\nContributions to chi-square:")
print(pd.DataFrame(contributions, index=table.index,
columns=table.columns).round(3))
statistic = contributions.sum()
dof = (table.shape[0] - 1) * (table.shape[1] - 1)
p_value = 1 - stats.chi2.cdf(statistic, dof)
print(f"\nchi2 = {statistic:.3f}, df = {dof}, p = {p_value:.4f}")
Note the degrees of freedom: (rows − 1) × (columns − 1). Unlike the goodness-of-fit test, here the margins are estimated from the data itself, and each estimated margin removes a degree of freedom. For a two-by-two table that leaves exactly one degree of freedom, which is why the two-variable test on binary outcomes is the degenerate case rather than the general one.
Running the library version
Once the arithmetic is understood, the library call is a one-liner — provided you pass the table in the orientation you intend and check the output against the hand calculation.
# The library call
chi2, p, dof, expected_arr = stats.chi2_contingency(table)
print(f"chi2({dof}) = {chi2:.3f}, p = {p:.4f}")
# Confirm against the manual calculation
assert np.isclose(chi2, statistic)
assert np.isclose(p, p_value)
# A second, larger example: survey responses by region
survey = pd.DataFrame(
[[45, 30, 25],
[20, 40, 35],
[50, 20, 15]],
index=["north", "south", "east"],
columns=["agree", "neutral", "disagree"],
)
chi2, p, dof, exp = stats.chi2_contingency(survey)
print(f"\nSurvey: chi2({dof}) = {chi2:.2f}, p = {p:.4f}")
print(pd.DataFrame(exp, index=survey.index, columns=survey.columns).round(1))
# Check the expected-count assumption before believing the p-value
below_five = (exp < 5).mean()
print(f"Cells with expected count below 5: {below_five:.0%}")
if below_five > 0.20 or exp.min() < 1:
print("WARNING: sparse table; pool categories or use an exact test.")
That expected-count check belongs in every script you write, not just the exploratory ones. It is the difference between a p-value you can defend and one that quietly rests on an approximation that does not apply.
Reading the association: residuals and effect size
A significant chi-square says the variables are associated; it does not say which cells carry the association or how strong it is. Standardised residuals answer the first question, and Cramér's V answers the second.
chi2, p, dof, exp = stats.chi2_contingency(table)
# Pearson residuals: (observed - expected) / sqrt(expected)
# Under independence these are roughly standard normal once scaled
resid_df = pd.DataFrame(
(table.to_numpy() - exp) / np.sqrt(exp),
index=table.index,
columns=table.columns,
)
print("Pearson residuals (|value| > 2 is notable):")
print(resid_df.round(2))
def cramers_v(chi2, n, r, k):
"""Effect size for a contingency table."""
return np.sqrt(chi2 / (n * (min(r, k) - 1)))
n = table.to_numpy().sum()
v = cramers_v(chi2, n, *table.shape)
print(f"\nCramer's V = {v:.3f} (n = {n})")
# Interpretation bands, roughly
for threshold, label in [(0.1, "small"), (0.3, "medium"), (0.5, "large")]:
if v >= threshold:
last = label
print(f"By conventional bands, this is a {last} association.")
Cramér's V ranges from zero to one and is defined for any table size, which makes it comparable across studies in a way the raw chi-square statistic never is. For two-by-two tables the related measure is the phi coefficient, which is numerically identical to Cramér's V in that special case; for larger tables phi inflates, which is why Cramér's V is the default report.
Two-by-two tables and the odds ratio
The two-by-two table is common enough to deserve its own treatment, because it supports an effect measure — the odds ratio — that is more interpretable than any correlation-style index.
# Binary predictor, binary outcome
twobytwo = pd.DataFrame(
[[50, 30], # treatment: improved, not improved
[35, 45]], # control
index=["treatment", "control"],
columns=["improved", "not_improved"],
)
chi2, p, dof, exp = stats.chi2_contingency(twobytwo)
print(f"chi2({dof}) = {chi2:.3f}, p = {p:.4f}")
a, b = twobytwo.loc["treatment"]
c, d = twobytwo.loc["control"]
odds_ratio = (a / b) / (c / d)
print(f"Odds ratio = {odds_ratio:.3f}")
# Confidence interval for the odds ratio (Woolf method)
se_log = np.sqrt(1/a + 1/b + 1/c + 1/d)
ci_low = np.exp(np.log(odds_ratio) - 1.96 * se_log)
ci_high = np.exp(np.log(odds_ratio) + 1.96 * se_log)
print(f"95% CI: ({ci_low:.2f}, {ci_high:.2f})")
# Yates' continuity correction, the conservative default for small 2x2
chi2_yates, p_yates, _, _ = stats.chi2_contingency(twobytwo, correction=True)
print(f"With Yates correction: chi2 = {chi2_yates:.3f}, p = {p_yates:.4f}")
# Fisher's exact test: exact, no approximation, for any 2x2
oddsratio, p_fisher = stats.fisher_exact(twobytwo)
print(f"Fisher's exact: p = {p_fisher:.4f}")
The odds ratio has an asymmetry that catches people out: a value of two means the odds doubled, but its reciprocal for the reversed table is one half, and zero is the natural floor rather than minus infinity. That is why confidence intervals for odds ratios are computed on the log scale and exponentiated back, and why a ratio near one with a wide interval is a study that has not yet decided anything.
Yates' correction deserves a brief note of caution. It shrinks the chi-square statistic toward zero by half a count per cell, which reduces the already-correct tendency of the uncorrected test to reject too often at small samples. Modern practice is mixed: some packages apply it by default for two-by-two tables, and many statisticians prefer reporting Fisher's exact result alongside it rather than choosing a side.
When the variables are ordinal
If either variable has a natural order — a Likert scale, age bands, severity grades — the chi-square test throws that structure away. It treats "strongly disagree" and "agree" as no more similar than "strongly disagree" and "strongly agree", which costs power and can miss a trend that runs monotonically through the table.
# Ordinal Likert response by treatment group
likert = pd.DataFrame(
[[10, 20, 30, 25, 15], # treatment
[25, 30, 25, 15, 5]], # control
index=["treatment", "control"],
columns=["strongly_disagree", "disagree", "neutral", "agree", "strongly_agree"],
)
chi2, p, dof, exp = stats.chi2_contingency(likert)
print(f"Standard chi-square: chi2({dof}) = {chi2:.2f}, p = {p:.4f}")
# Trend test: score the categories and compare mean scores
scores = np.arange(1, 6)
treatment_scores = np.repeat(scores, likert.loc["treatment"])
control_scores = np.repeat(scores, likert.loc["control"])
t_stat, p_trend = stats.ttest_ind(treatment_scores, control_scores,
equal_var=False)
print(f"Trend (Welch t on scores): t = {t_stat:.2f}, p = {p_trend:.4f}")
# Mann-Whitney on the same scores: the rank-based alternative
u_stat, p_mw = stats.mannwhitneyu(treatment_scores, control_scores)
print(f"Mann-Whitney U: p = {p_mw:.4f}")
The trend test is usually more powerful precisely because it uses the order, and the honest report states both: the omnibus chi-square answers "is anything different", the trend analysis answers "in which direction". A significant chi-square with a non-significant trend, or the reverse, are both informative outcomes rather than contradictions.
Sparse tables and exact alternatives
Small samples with many categories produce tables where expected counts fall below five across most cells, and the chi-square approximation becomes unreliable in a way that inflates the Type I error rate. Three remedies exist, and the choice depends on what you are willing to assume.
| Situation | Remedy | Trade-off |
|---|---|---|
| A few sparse cells | pool categories | coarser hypothesis, simpler table |
| Two-by-two table | Fisher's exact test | exact but conservative |
| Larger sparse table | Monte Carlo chi-square | compute instead of assumptions |
# Monte Carlo chi-square for a sparse table, via simulation
sparse = np.array([[3, 1, 0],
[1, 2, 1],
[0, 1, 3]])
row_tot = sparse.sum(axis=1)
col_tot = sparse.sum(axis=0)
grand = sparse.sum()
exp_sparse = np.outer(row_tot, col_tot) / grand
print("Expected counts:\n", exp_sparse.round(2))
def chi2_stat(obs, exp):
return ((obs - exp) ** 2 / exp).sum()
obs_stat = chi2_stat(sparse, exp_sparse)
rng = np.random.default_rng(7)
sims = rng.multinomial(grand, (exp_sparse / grand).ravel(), size=20000)
sims = sims.reshape(-1, *sparse.shape)
exp_broadcast = np.broadcast_to(exp_sparse, sims.shape)
sim_stats = ((sims - exp_broadcast) ** 2 / exp_broadcast).sum(axis=(1, 2))
mc_p = (sim_stats >= obs_stat).mean()
print(f"Observed chi2 = {obs_stat:.3f}, Monte Carlo p = {mc_p:.4f}")
# scipy's built-in Monte Carlo option
mc_chi2, mc_p2, _, _ = stats.chi2_contingency(
sparse, correction=False, lambda_="log-likelihood",
)
print(f"scipy G-test statistic = {mc_chi2:.3f}")
Pooling remains the most underused remedy. If three response categories each hold two observations, merging the two least frequent into a single "other" category often restores validity without materially changing the question — and it must be decided on substantive grounds before the p-value is seen, never after.
A worked analysis end to end
The full workflow in one script: check assumptions, run the test, quantify the association, locate the drivers, and decide what to do about it.
churn = pd.DataFrame(
[[210, 90], [160, 60], [80, 40], [30, 30]],
index=["email", "chat", "phone", "self_service"],
columns=["retained", "churned"],
)
# 1. Assumptions
chi2, p, dof, exp = stats.chi2_contingency(churn)
n = churn.to_numpy().sum()
print(f"Min expected count: {exp.min():.1f}")
print(f"Cells below 5: {(exp < 5).sum()} of {exp.size}")
# 2. Test
print(f"\nchi2({dof}) = {chi2:.2f}, p = {p:.4f}")
# 3. Effect size
v = cramers_v(chi2, n, *churn.shape)
print(f"Cramer's V = {v:.3f}")
# 4. Drivers
resid = (churn.to_numpy() - exp) / np.sqrt(exp)
resid_df = pd.DataFrame(resid, index=churn.index, columns=churn.columns)
print("\nResiduals (cells beyond |2| drive the result):")
print(resid_df.round(2))
drivers = (resid_df.abs() > 2).stack()
print("Notable cells:", list(drivers[drivers].index))
# 5. Action
if p < 0.05 and v > 0.2:
print("Act: support channel is associated with churn at a meaningful size.")
else:
print("Hold: no actionable association at this sample size.")
Step five is the one that separates analysis from statistics. A p-value of 0.03 with a Cramér's V of 0.05 is a real but negligible association, and reporting it as a finding without that context invites a decision built on noise. The effect size is what tells you whether the finding deserves a ticket.
Mistakes that misread the table
Common Mistakes
Interpreting a significant chi-square as causal
Fix: The test detects association only; the design must support any causal claim.
Ignoring expected counts below five
Fix: Check them every time, and pool categories or switch to an exact test when they fail.
Reporting the p-value without an effect size
Fix: Add Cramér's V so the magnitude of the association is visible.
Pooling sparse categories after seeing the results
Fix: Fix the grouping from domain knowledge first, or the test is circular.
Using chi-square on ordinal variables as if they were nominal
Fix: Add a trend test or rank-based analysis that uses the order.
Treating a large table's chi-square as interpretable on its own
Fix: With many categories the statistic grows mechanically; rely on residuals and V.
Forgetting that Yates' correction is conservative
Fix: Report Fisher's exact alongside it for two-by-two tables rather than choosing blindly.
Practices that keep the analysis trustworthy
Best Practices
- Print expected counts and the proportion of sparse cells before trusting any p-value.
- Report the statistic, degrees of freedom, p-value, and Cramér's V together.
- Use standardised residuals to name the cells that drive a significant result.
- Add a trend analysis when either variable is ordinal.
- Prefer Fisher's exact for two-by-two tables with small counts.
- Pool sparse categories on documented, substantive grounds.
- State clearly that the test establishes association, not causation.
- Check the table orientation before calling the library; rows and columns are easy to transpose.
Key takeaways
Key Takeaways
- The test asks whether column proportions are the same across every row of a contingency table.
- Expected counts come from the margins: row total times column total over grand total.
- Degrees of freedom are (rows − 1) times (columns − 1), because the margins are estimated.
- Standardised residuals reveal which cells carry the association.
- Cramér's V puts the association's strength on a zero-to-one scale.
- Two-by-two tables add the odds ratio, with its interval computed on the log scale.
- Sparse tables break the approximation; pool, go exact, or simulate.
- Association is not causation, and significance is not importance.
Where to go next
- Chi-Square Goodness-of-Fit Test — the one-variable sibling for testing a specified distribution.
- Contingency Tables — constructing and reading cross-tabulations.
- Cramér's V — the effect size this test leans on.
- Multiple Testing Problem — what to do when many tables are tested at once.