Contingency Tables
Descriptive Statistics
Test Whether Your Categorical Variables Are Truly Independent
Contingency tables let you move beyond descriptive counts to formally test whether two categorical variables are associated — and how strongly.
- Construct tables — Build frequency matrices that cross-tabulate categorical variables
- Calculate expected frequencies — Determine what counts would look like under independence
- Apply chi-square testing — Quantify whether observed deviations from independence are significant
- Measure association strength — Use Cramér's V and Phi to assess how related your variables are
The chi-square test transforms a table of numbers into a verdict about independence.
What You'll Learn
- 1Cross-tabulate raw records into row, column, and joint frequencies
- 2Derive every expected cell count from row and column totals
- 3Compute the chi-square statistic, its degrees of freedom, and the decision rule
- 4Separate statistical significance from practical strength using phi and Cramér's V
What are Contingency Tables?
Every record lands in exactly one cell, because it carries one level of the row variable and one level of the column variable. A table with rows and columns holds cells whose sum is always the sample size . Row totals form the marginal distribution of the row variable, column totals form the marginal distribution of the column variable, and a single cell is a joint frequency: the count of records satisfying both conditions at once.
Four kinds of numbers appear in a well-built table, and confusing them is the most common reading error:
| Quantity | How you get it | Question it answers |
|---|---|---|
| Joint frequency | One cell count | How many records are in this combination? |
| Row total | Sum across a row | How many records have this row level at all? |
| Row percentage | Cell divided by its row total | Within this row level, how common is each column level? |
| Column percentage | Cell divided by its column total | Within this column level, how common is each row level? |
import numpy as np
import pandas as pd
from scipy import stats
# Build a contingency table
data = pd.DataFrame({
'Treatment': ['Drug']*50 + ['Placebo']*50,
'Outcome': ['Improved']*35 + ['Not Improved']*15 + ['Improved']*20 + ['Not Improved']*30
})
ct = pd.crosstab(data['Treatment'], data['Outcome'], margins=True, margins_name='Total')
print("Contingency Table with margins:")
print(ct)
# Joint frequencies without margins, plus normalized views
core = pd.crosstab(data['Treatment'], data['Outcome'])
print("\nRow percentages (risk within each treatment):")
print((100 * core.div(core.sum(axis=1), axis=0)).round(1))
print("\nColumn percentages (treatment mix inside each outcome):")
print((100 * core.div(core.sum(axis=0), axis=1)).round(1))
Reading the Table: Margins, Percentages, and Direction
Pick the denominator before you pick the story. If rows are the exposure (drug versus placebo) and columns are the outcome, row percentages give the risk in each group, which is what a reader wants. Divide by the total for whichever variable you are conditioning on.
Take the table above: 35 of 50 drug patients improved, so the row percentage is , while 20 of 50 placebo patients improved, giving . The risk difference is 30 percentage points, the relative risk is , and the odds ratio compares the odds of improvement in each arm: . These three summaries answer different questions — absolute benefit, times more likely, and times greater odds — so quoting only one hides part of the picture.
Direction decides what you may call the cause: conditioning on the treatment tells you about outcomes, conditioning on the outcome tells you about case mix. The chi-square statistic is unchanged if you transpose the table, so state which variable you treated as the exposure.
Expected Frequencies Under Independence
The null hypothesis of independence says the two variables do not interact: knowing the row level tells you nothing about the column level. If that is true, the proportion of records in any column should be the same in every row, so the count you would expect in a cell is the column's overall share applied to that row total.
The second form shows where the formula comes from: sample size times the marginal probability of row times the marginal probability of column , which is exactly what independence asserts. For our 100-patient table the row totals are 50 and 50, the column totals are 55 improved and 45 not improved, so:
- , and
Expected counts need not be whole numbers, and their row and column sums reproduce the observed margins exactly — if your expected table does not add back to the margins, you divided by the wrong total.
Assumptions the test depends on
Chi-Square Test
The statistic sums the squared gap between observed and expected counts in every cell, weighted by the size of the expectation so that large-count cells are not over-penalized:
chi2, p_value, dof, expected = stats.chi2_contingency(core)
print(f"\nChi-square statistic = {chi2:.4f}")
print(f"p-value = {p_value:.4f}")
print(f"Degrees of freedom = {dof}")
print(f"\nExpected frequencies:")
print(pd.DataFrame(expected, index=core.index, columns=core.columns).round(2))
# Standardized residuals: z-score for each cell
resid = (core.values - expected) / np.sqrt(expected)
print(f"\nResiduals over sqrt(E):\n{np.round(resid, 2)}")
| Component | Description |
|---|---|
| χ² statistic | Measures discrepancy between observed and expected frequencies |
| df | (rows - 1) × (columns - 1) |
| p-value | Probability of observing χ² this large if variables are independent |
Degrees of freedom count the cells you may fill freely once the margins are fixed: each row loses one constraint and each column loses one, leaving , which is a single degree of freedom for a two-by-two table. The decision rule is the usual one: reject independence when the p-value falls below your pre-declared alpha, typically 0.05.
A significant result means the margins alone do not explain the cell counts. It does not say which cells drive the discrepancy, how strong the association is, or whether it is causal. Cell-level localization comes from standardized residuals — the residual divided by the square root of its expected count — where values beyond roughly plus or minus 2 point at the cells doing the work.
Worked Example: Hand-Computing the Statistic
Swapping two columns leaves every squared gap unchanged, so the test reports only that something is going on — direction has to come from the percentages.
Fisher's Exact Test
For small sample sizes (expected frequencies less than 5), use Fisher's exact test:
# Small sample example
small_table = np.array([[5, 2], [1, 4]])
odds_ratio, p_fisher = stats.fisher_exact(small_table)
print(f"Small table:\n{small_table}")
print(f"Odds ratio = {odds_ratio:.4f}")
print(f"Fisher p = {p_fisher:.4f}")
Fisher conditions on both margins and sums the hypergeometric probability of every table no more likely than the one you observed, so it never leans on the large-sample approximation chi-square needs. The price is combinatorial growth: for tables larger than two-by-two, software switches to a Fisher–Freeman–Halton variant or a Monte Carlo estimate. SciPy exposes stats.fisher_exact for two-by-two input and stats.chi2_contingency for everything else.
Measures of Association
A p-value answers "is there an association", and never "how big is it". Effect sizes fill that gap, and they behave differently across table shapes.
# Cramér's V for any table size
n = core.values.sum()
r, c = core.shape
v = np.sqrt(chi2 / (n * min(r-1, c-1)))
print(f"Cramér's V = {v:.4f}")
# Phi for 2x2 tables
phi = np.sqrt(chi2 / n)
print(f"Phi (φ) = {phi:.4f}")
| Measure | Formula | Range | Rough interpretation |
|---|---|---|---|
| Phi (2×2 only) | sqrt(chi2 / n) | 0 to 1 | 0.1 small, 0.3 medium, 0.5 large |
| Cramér's V (any size) | sqrt(chi2 / (n × min(r-1, c-1))) | 0 to 1 | Same anchors, valid for square tables |
| Odds ratio | (a×d)/(b×c) | 0 to infinity | 1 = no association; log scale is symmetric |
| Cohen's w | sqrt(sum of squared residual proportions) | 0 to 1 | 0.1 / 0.3 / 0.5 anchors |
The 0.1, 0.3 and 0.5 anchors were proposed as rough small, medium and large benchmarks, so quote the numeric value alongside the label. In a large sample a phi of 0.05 can be significant yet remain practically irrelevant, which is exactly why the effect size belongs next to the p-value.
Choosing the Right Test for Your Table
| Situation | Test to run | Why this one |
|---|---|---|
| Two categorical variables, expectations healthy | Chi-square test of independence | Fast, well understood, works for any table shape |
| Expectations below 5, or a tiny 2×2 | Fisher's exact test | Exact hypergeometric p-value, no approximation |
| Same subjects measured twice (before/after) | McNemar's test | Paired data violate the independence assumption |
| Two ordinal variables | Linear-by-linear association or Cochran–Armitage | Uses the ordering that chi-square throws away |
| Survey data with sampling weights | Rao–Scott adjusted chi-square | Design effects inflate the naive statistic |
| More than two related samples | Cochran's Q | Generalization of McNemar to k matched groups |
The pairing row is the trap that catches most analysts: if the same 40 patients are scored before and after treatment, each patient contributes two cells, so an ordinary chi-square inflates the statistic. Matched pairs need a test built for them.
Contingency Tables in Machine Learning
| ML Application | Usage | Why |
|---|---|---|
| Confusion matrix | Prediction vs actual | Core classification metric |
| Lift table | Predicted probability vs actual outcome | Model calibration |
| Feature analysis | Two categorical features | Relationship discovery |
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix, classification_report
np.random.seed(42)
y_true = np.random.choice([0, 1, 2], 300, p=[0.5, 0.3, 0.2])
y_pred = np.random.choice([0, 1, 2], 300, p=[0.5, 0.3, 0.2])
cm = pd.DataFrame(confusion_matrix(y_true, y_pred),
columns=['Pred 0', 'Pred 1', 'Pred 2'],
index=['True 0', 'True 1', 'True 2'])
print("Confusion matrix (contingency table):")
print(cm)
print(f"\nAccuracy: {np.trace(cm.values) / cm.values.sum():.3f}")
# Row-normalized confusion matrix reads as recall per class
print("\nRow-normalized (recall per class):")
print((100 * cm.div(cm.sum(axis=1), axis=0)).round(1))
A confusion matrix is a contingency table whose rows are the true labels and whose columns are the predictions, so everything on this page transfers: row percentages give recall, a chi-square of homogeneity asks whether error rates differ by class, and Cramér's V summarizes how far predictions sit from the truth.
Frequently Asked Questions
Do I need the same sample size in every cell?
No. Chi-square works with unbalanced tables; what matters is the expected count in each cell, not the observed count. Totals of 200 and 40 are fine when every expectation clears 5, while a balanced table of 6 and 6 already fails.
What does a significant chi-square not prove?
Not causation, not which cell drives the result, and not how strong the association is. Causality needs a manipulable exposure, attribution needs standardized residuals, and strength needs phi or Cramér's V.
Can I run chi-square on a three-way table?
Not directly. Use a stratified method such as the Mantel–Haenszel procedure, which pools two-way tables while controlling for the third variable, or a log-linear model.
Common Mistakes
Reporting row percentages when the column variable is the exposure
Fix: Condition on the variable you treat as the cause: rows as exposure means dividing by row totals.
Running chi-square on paired or repeated measures data
Fix: Matched before-and-after counts need McNemar's test, because each subject contributes two dependent observations.
Treating a tiny p-value as a large effect
Fix: Pair the test with phi or Cramér's V and state the effect size next to the p-value.
Key Takeaways
- A contingency table holds joint counts in its cells, marginal totals on its edges, and percentages that depend entirely on which total you divide by
- Expected counts under independence are row total times column total divided by the grand total, and they must add back to the observed margins
- The chi-square statistic sums (observed minus expected) squared over expected across all cells, with (r−1)(c−1) degrees of freedom
- Significance and strength are separate claims: chi-square and Fisher answer whether, phi and Cramér's V answer how much
Interview Questions
Q1: How do you compute an expected count, and what is it?
Row total times column total divided by the grand total. It is the cell count you would see if the two variables were independent, so comparing it with the observed count is the entire basis of chi-square.
Q2: When do you reach for Fisher's exact test?
When any expected frequency is below 5, when n is small, or when the table is two-by-two and an exact p-value is required. It conditions on both margins and sums hypergeometric probabilities.
Q3: What are the degrees of freedom for a 3 by 4 table?
(3−1) times (4−1) = 6, because each row and each column contributes one linear constraint among the cell counts.
Q4: Chi-square is significant but Cramér's V is 0.05 — what do you report?
Both: the association is detectable but practically negligible, so lead with the effect size and the sample size rather than the p-value.
Always check expected frequencies before interpreting chi-square results — the test's validity depends on having enough observations in each cell.