Cross-Tabulation
Descriptive Statistics
Unlock the Hidden Relationships in Your Categorical Data
Cross-tabulation reveals how two categorical variables interact — turning raw counts into actionable insights about association and dependence.
- Discover patterns — See how categories of one variable distribute across another
- Compare groups — Use row, column, and total percentages to uncover disparities
- Test significance — Apply chi-square testing to determine if associations are real or due to chance
What You'll Learn
- 1Construct a contingency table and verify every row, column, and grand total before analyzing
- 2Compute row, column, and total percentages and state which question each answers
- 3Calculate expected frequencies and hand-check a chi-square statistic cell by cell
- 4Follow significance with Cramér's V so effect size is reported alongside the p-value
Correlation coefficients need numeric inputs, but many of the questions worth asking are categorical: does gender relate to product preference, does a treatment arm change the recovery rate, does a predicted class match the actual label? Cross-tabulation is the tool that answers them by stacking joint counts into a matrix and reading structure off the margins. Every confusion matrix, every A/B test readout, and every market-research banner starts life as a contingency table. The craft lies not in producing the counts — one crosstab call — but in choosing the right percentages, testing whether the pattern beats chance, and quantifying how much it matters.
Building a Contingency Table That Adds Up
A contingency table places one categorical variable along the rows, another along the columns, and the joint counts in the cells. Take a preference survey of 100 respondents balanced by gender: among 50 men, 15 prefer tea, 25 coffee, 10 juice; among 50 women, 20 prefer tea, 15 coffee, 15 juice. The table writes those counts in a 2 by 3 grid whose row totals (50 and 50), column totals (35, 40, and 25), and grand total (100) all reconcile. That reconciliation is not busywork — mismatched margins reveal dropped NaN rows, silent category typos ("Male " with a trailing space creating a phantom level), and filters that fired twice. A table that does not add up cannot be trusted downstream, so the totals check belongs in the ingestion tests, not in a slide footnote.
import numpy as np
import pandas as pd
from scipy import stats
survey = pd.DataFrame({
'Gender': ['Male'] * 50 + ['Female'] * 50,
'Preference': (['Tea'] * 15 + ['Coffee'] * 25 + ['Juice'] * 10 +
['Tea'] * 20 + ['Coffee'] * 15 + ['Juice'] * 15),
})
ct = pd.crosstab(survey['Gender'], survey['Preference'], margins=True)
print("Gender x Preference (counts):")
print(ct)
assert ct.loc['All', 'All'] == len(survey)
print(f"\nGrand total matches n = {len(survey)}: OK")
Row, Column, and Total Percentages
Raw counts answer "how many," but comparisons need percentages, and the denominator you pick changes the question entirely. Row percentages divide each cell by its row total: within men, 30 percent prefer tea, 50 percent coffee, 20 percent juice; within women, 40, 30, and 30 percent. That normalizes away the equal group sizes and answers "does preference mix differ by gender?" Column percentages divide by column totals instead, answering the mirror question "what is the gender composition of each preference group?" — coffee drinkers are 62.5 percent male (25 of 40) while juice drinkers are only 40 percent male. Total percentages divide by the grand total and describe the whole sample's cell shares, useful for size but useless for group contrast. The habit to build: name the denominator out loud before quoting any percentage from a table.
| Percentage type | Denominator | Answers | Value in the coffee-male cell |
|---|---|---|---|
| Row | Row total (50) | Preference mix within gender | 25/50 = 50.0% |
| Column | Column total (40) | Gender mix within preference | 25/40 = 62.5% |
| Total | Grand total (100) | Share of whole sample | 25/100 = 25.0% |
ct_row = pd.crosstab(survey['Gender'], survey['Preference'], normalize='index') * 100
ct_col = pd.crosstab(survey['Gender'], survey['Preference'], normalize='columns') * 100
ct_all = pd.crosstab(survey['Gender'], survey['Preference'], normalize='all') * 100
print("Row percentages (within gender):")
print(ct_row.round(1))
print("\nColumn percentages (within preference):")
print(ct_col.round(1))
print("\nTotal percentages (share of sample):")
print(ct_all.round(1))
Reading Disparities from Conditional Distributions
The row-conditional distributions expose the headline contrast: coffee preference runs 50 percent among men against 30 percent among women, a 20-point gap and a relative risk of . Tea moves the other way, 30 versus 40 percent. Before declaring a finding, three readings keep the interpretation honest. Compare within rows, not across raw counts, because group sizes differ in almost every real survey. Check whether the gap is symmetric — here the 20-point coffee gap mirrors a 10-point tea gap and a 5-point juice gap, consistent with a single reallocation rather than three independent effects. And remember that association licenses no causal claim: gender may proxy for age, region, or time of day the survey ran, and only a designed experiment or a careful adjustment strategy separates those explanations.
male = ct_row.loc['Male']
female = ct_row.loc['Female']
gap = male - female
print("Within-gender preference percentages and gaps (male minus female):")
for pref in ct_row.columns:
print(f" {pref:7s}: male {male[pref]:5.1f}% | female {female[pref]:5.1f}% | gap {gap[pref]:+5.1f} pts")
p_coffee_m, p_coffee_f = male['Coffee'] / 100, female['Coffee'] / 100
print(f"\nRelative risk for coffee (male vs female): {p_coffee_m / p_coffee_f:.2f}")
The Chi-Square Test, One Cell at a Time
Visual gaps need a chance benchmark. The chi-square test of independence compares observed counts to the counts expected if the two variables were unrelated, with each expected frequency computed from the margins alone:
For the male-coffee cell, the expected count is against an observed 25. Running all six cells: expected values are 17.5, 20, and 12.5 in each row (the rows being equal-sized), and the contributions are 0.357, 1.250, 0.500, 0.357, 1.250, and 0.500. Their sum is on degrees of freedom. For two degrees of freedom the survival function has the closed form , giving . At the conventional 0.05 threshold the data do not reject independence — the observed gap is compatible with sampling noise at . The practical lesson: detect the effect, size it, then decide whether the sample can resolve it, rather than letting a single p-value narrate the whole story.
| Cell | Observed | Expected | |
|---|---|---|---|
| Male, Tea | 15 | 17.5 | 0.357 |
| Male, Coffee | 25 | 20.0 | 1.250 |
| Male, Juice | 10 | 12.5 | 0.500 |
| Female, Tea | 20 | 17.5 | 0.357 |
| Female, Coffee | 15 | 20.0 | 1.250 |
| Female, Juice | 15 | 12.5 | 0.500 |
| Total | 100 | 100 | 4.214 |
The test's assumptions deserve respect: observations must be independent, categories mutually exclusive, and expected frequencies comfortably above 5 — a rule of thumb that fails for sparse tables and sends you toward Fisher's exact test or Monte Carlo p-values instead.
ct_counts = pd.crosstab(survey['Gender'], survey['Preference'])
chi2, p_value, dof, expected = stats.chi2_contingency(ct_counts)
print(f"Chi-square = {chi2:.4f} (hand check: 4.2143)")
print(f"Degrees of freedom = {dof}")
print(f"p-value = {p_value:.4f} (df=2 closed form e^(-chi2/2): {np.exp(-chi2 / 2):.4f})")
print("\nExpected frequencies under independence:")
print(pd.DataFrame(expected, index=ct_counts.index, columns=ct_counts.columns).round(2))
print(f"\nAll expected counts above 5: {np.all(expected > 5)}")
Three-Way Tables and the Confounder Problem
Adding a third variable — age group, region, or survey mode — turns the grid into stacked two-way tables, one per level of the new variable. Stratification is how you interrogate confounding: if the gender-preference association vanishes inside every age band, age was carrying it, a phenomenon known as Simpson's paradox when the aggregate and stratified directions actually reverse. The reversal is not a curiosity reserved for textbooks; it has appeared in claims about approval rates, treatment outcomes, and baseball batting averages. The operational workflow is to cross the two primary variables within each stratum, compare stratum-specific percentages to the pooled figure, and only then decide whether a single headline table is defensible or whether the strata must be reported — or adjusted for — separately. pandas stacks the tables by passing a list of row variables to crosstab, with margins adding the totals that keep each slice auditable.
survey['Age_Group'] = ['18-34'] * 30 + ['35-54'] * 40 + ['55+'] * 30
three_way = pd.crosstab(
[survey['Age_Group'], survey['Gender']],
survey['Preference'],
margins=True,
)
print("Three-way table (age group x gender, by preference):")
print(three_way)
pooled = pd.crosstab(survey['Gender'], survey['Preference'], normalize='index') * 100
print("\nPooled row percentages for comparison with strata:")
print(pooled.round(1))
Effect Size: Cramér's V After Significance
A significant chi-square says an association exists, not that it is large. Cramér's V rescales the statistic into a 0-to-1 quantity comparable across tables of different sizes:
For our table, , which lands in the small-to-moderate band for a 2-by-3 design. Cohen's benchmarks — near 0.1 small, 0.3 medium, 0.5 large — are rough but force the conversation toward practical importance. This two-step discipline, significance then effect size, is the standard defense against two failure modes: the underpowered study that misses a large real effect, and the overpowered study that flags a trivial one. Confusion matrices get the same treatment: report the chi-square that the prediction and ground-truth labels are independent, then follow with Cramér's V or the per-class rates that describe how badly they disagree.
min_dim = min(ct_counts.shape[0] - 1, ct_counts.shape[1] - 1)
cramers_v = np.sqrt(chi2 / (len(survey) * min_dim))
print(f"Chi-square = {chi2:.4f}, n = {len(survey)}, min(r-1, c-1) = {min_dim}")
print(f"Cramer's V = {cramers_v:.4f} (small-to-moderate association)")
# Heatmap of row percentages makes the pattern legible at a glance
import matplotlib.pyplot as plt
import seaborn as sns
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
sns.heatmap(ct_counts, annot=True, fmt='d', cmap='Blues', ax=axes[0])
axes[0].set_title('Counts')
sns.heatmap(ct_row, annot=True, fmt='.1f', cmap='Blues', ax=axes[1])
axes[1].set_title('Row percentages (%)')
plt.tight_layout()
plt.show()
💡Percentages before p-values
Common Mistakes
Quoting percentages without naming the denominator
Fix: State whether the figure is a row, column, or total percentage; the same cell yields 50%, 62.5%, and 25% under the three conventions.
Running chi-square on a sparse table with expected counts below 5
Fix: Collapse categories or switch to Fisher's exact test or a Monte Carlo chi-square when expected frequencies fall below the threshold.
Stopping at the p-value and ignoring effect size
Fix: Report Cramér's V (or the risk ratio) next to the chi-square so readers can judge practical importance, not just detectability.
Best Practices
- Assert row, column, and grand totals against the raw record count at ingestion
- Always pair contingency tables with a row-percentage view for group comparisons
- Check expected frequencies before trusting a chi-square result
- Stratify by likely confounders before publishing any association claim
Key Takeaways
- Contingency tables hold joint counts; row, column, and total percentages answer three different questions from the same cells
- Expected frequencies come from the margins alone: E = row total times column total over n
- Chi-square sums (O − E)² / E across cells with degrees of freedom (r − 1)(c − 1)
- Cramér's V follows significance to quantify how large the association actually is
Frequently Asked Questions
What is the difference between a cross-tab and a confusion matrix?
A confusion matrix is a cross-tabulation with a fixed orientation: predicted classes as rows, actual classes as columns. The same chi-square, row-percentage, and Cramér's V machinery applies to both, which is why classification diagnostics and survey analysis share a toolkit.
How many categories is too many for one table?
Usability degrades long before statistics do. Once a dimension exceeds about six levels, the grid becomes unreadable and expected counts fall below chi-square thresholds — collapse rare levels into "other," pivot to a mosaic plot, or move to a log-linear model.
Can cross-tabulation handle ordered categories?
Yes, though the standard chi-square ignores the ordering. If the columns are ordered — satisfaction rated low, medium, high — trend tests such as the Cochran-Armitage test or a linear-by-linear association term extract more power by using the rank information the general test discards.
Interview Questions
Q1: You see P(A and B) in a table. How do you test whether A and B are independent?
Compute expected counts as row total times column total over n for every cell, then sum (O − E)² / E to get chi-square on (r − 1)(c − 1) degrees of freedom. A small p-value rejects independence; Cramér's V sizes whatever association remains.
Q2: Row percentages and column percentages disagree in direction. Which is right?
Both, for different questions. Row percentages compare the distribution of the column variable within each row category; column percentages compare row composition within each column category. Pick the denominator that matches the question you are asking.
Q3: What does Cramér's V add that the p-value does not?
The p-value measures detectability, which grows with sample size; Cramér's V measures association strength on a 0-to-1 scale. A tiny p-value can accompany a negligible V in a large sample, so report both.