Module 4 · Intermediate · Relationships between variables

Contingency tables: relationships in categories

Measure how two categorical columns are related: crosstabs, row and column percentages, expected counts and Cramér's V, with penguins and the Titanic.

By theprogrammers team · · 10 min read

Is a penguin's species related to the island it lives on? Is a Titanic passenger's class related to whether they survived? These columns are categories, not numbers, so correlation can't measure them: there's no "average island" or straight line through species. Instead, you count.

A contingency table (or crosstab) counts how many rows fall into each combination of two categories. Turned into percentages, compared with what you'd expect if the columns were independent, and summed up into one number called Cramér's V, it answers "are these two categories related, and how strongly?" It's the module's last lesson, and it ties together counting, conditional probability and independence.

What you need first: conditional probability explained, independent events explained and types of data.

Key terms

  • Contingency table (or crosstab): a table of counts for every combination of two categorical columns.
  • Marginal totals: the row and column totals, along the table's edges (its margins).
  • Row percentages: each row divided by its row total. Each row then shows a conditional distribution, such as P(island | species).
  • Expected count: the count a cell would have if the two columns were independent.
  • Cramér's V: a number from 0 (no relationship) to 1 (one category completely determines the other) measuring how strongly two categorical columns are related.

Count every combination

Download the data: penguins.csv (15 KB), or from the original source, the palmerpenguins project, and titanic.csv (58 KB), or from the original source, the seaborn-data repository on GitHub. The code below loads both for you, so you only need the files to open them in a spreadsheet or work offline: load them with pd.read_csv("penguins.csv") and pd.read_csv("titanic.csv").

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

penguins = sns.load_dataset("penguins")
titanic = sns.load_dataset("titanic")
print(pd.crosstab(penguins["species"], penguins["island"], margins=True))
island     Biscoe  Dream  Torgersen  All
species                                 
Adelie         44     56         52  152
Chinstrap       0     68          0   68
Gentoo        124      0          0  124
All           168    124         52  344

pd.crosstab(rows, columns, margins=True) counts every combination and adds the totals, labelled All.

The zeros jump out. Gentoos live only on Biscoe; Chinstraps only on Dream; Adelies on all three islands. Species and island are clearly related.

Percentages: which way do you divide?

Raw counts are hard to compare when groups differ in size. Turn them into percentages, but choose the direction to match your question:

print("Row %: for each species, where does it live?")
print(pd.crosstab(penguins["species"], penguins["island"], normalize="index").round(2))
print()
print("Column %: on each island, which species live there?")
print(pd.crosstab(penguins["species"], penguins["island"], normalize="columns").round(2))
Row %: for each species, where does it live?
island     Biscoe  Dream  Torgersen
species                            
Adelie       0.29   0.37       0.34
Chinstrap    0.00   1.00       0.00
Gentoo       1.00   0.00       0.00

Column %: on each island, which species live there?
island     Biscoe  Dream  Torgersen
species                            
Adelie       0.26   0.45        1.0
Chinstrap    0.00   0.55        0.0
Gentoo       0.74   0.00        0.0
  • normalize="index" divides each row by its total, so each row adds to 1: P(island | species).
  • normalize="columns" divides each column by its total, so each column adds to 1: P(species | island).

These are the two directions of conditional probability. "What share of Adelies live on Torgersen?" and "What share of Torgersen penguins are Adelies?" are different questions with different answers: every penguin on Torgersen is an Adelie, but only about a third of Adelies live there. Decide which you're asking before you divide.

A 100% stacked bar chart shows the column percentages at a glance:

shares = pd.crosstab(penguins["island"], penguins["species"], normalize="index")
ax = shares.plot(kind="barh", stacked=True, color=["#d9a05a", "#c2410c", "#0f766e"], figsize=(8, 3.2))
ax.set_xlabel("Share of penguins on the island")
ax.set_ylabel("")
ax.set_title("Which species live on each island")
ax.legend(title="species", bbox_to_anchor=(1, 1))
plt.show()
A horizontal 100% stacked bar chart with one bar per island. Biscoe is about one quarter Adelie and three quarters Gentoo. Dream is just under half Adelie and just over half Chinstrap. Torgersen is entirely Adelie.

stacked=True piles each species on top of the last, and because the shares in each row add to 1, every bar has the same length.

If species and island were independent, every bar would have the same mix. Very different mixes mean a strong relationship.

Expected counts: what would independence look like?

To judge how far a table is from independence, work out what each cell would contain if the two columns were independent. Take Titanic class and survival. Overall, 38.4% of passengers survived. If survival didn't depend on class, 38.4% of each class would have survived:

expected count = row total × column total ÷ grand total

observed = pd.crosstab(titanic["class"], titanic["survived"])
row_totals = observed.sum(axis=1).to_numpy()[:, None]
col_totals = observed.sum(axis=0).to_numpy()[None, :]
expected = pd.DataFrame(row_totals * col_totals / observed.to_numpy().sum(),
                        index=observed.index, columns=observed.columns)
print("observed:"); print(observed)
print("\nexpected if independent:"); print(expected.round(1))
print("\nobserved − expected:"); print((observed - expected).round(1))
observed:
survived    0    1
class             
First      80  136
Second     97   87
Third     372  119

expected if independent:
survived      0      1
class                 
First     133.1   82.9
Second    113.4   70.6
Third     302.5  188.5

observed − expected:
survived     0     1
class               
First    -53.1  53.1
Second   -16.4  16.4
Third     69.5 -69.5
  • [:, None] and [None, :] turn the totals into a column and a row, so multiplying them gives every combination of row total and column total at once. (This is called broadcasting.)
  • Dividing by the grand total gives the expected count for each cell.

The formula is just the multiplication rule for independent events: P(first class and survived) = P(first class) × P(survived), multiplied by the number of passengers.

Read the last table. First class has far more survivors than independence predicts; third class far fewer. The bigger these gaps, the stronger the relationship.

One number for strength: Cramér's V

To compare relationships across tables, squash the gaps into one number. Cramér's V does this: 0 means the table matches the expected counts (independent), 1 means one category completely determines the other. SciPy computes it:

from scipy.stats.contingency import association

pairs = {"penguin species vs island": (penguins["species"], penguins["island"]),
         "penguin species vs sex": (penguins["species"], penguins["sex"]),
         "Titanic class vs survived": (titanic["class"], titanic["survived"]),
         "Titanic sex vs survived": (titanic["sex"], titanic["survived"])}
for name, (a, b) in pairs.items():
    print(f"{name:28} Cramér's V = {association(pd.crosstab(a, b)):.3f}")
penguin species vs island    Cramér's V = 0.660
penguin species vs sex       Cramér's V = 0.012
Titanic class vs survived    Cramér's V = 0.340
Titanic sex vs survived      Cramér's V = 0.543

association(table) takes a contingency table of counts and returns Cramér's V (its default method). pd.crosstab skips rows where either column is missing.

The ranking matches everything you've seen: species and island are strongly related; species and sex hardly at all (from independent events); on the Titanic, sex was more strongly related to survival than class was. A rough guide: below 0.1 is negligible, 0.1 to 0.3 weak, 0.3 to 0.5 moderate, above 0.5 strong.

Under the hood, Cramér's V is built from a sum of squared (observed − expected) gaps, called the chi-square statistic. The hypothesis testing module uses the same statistic to test whether a relationship could be chance.

Watch out for small counts

With small tables, percentages swing wildly. A category with 5 rows where 4 survived shows 80%, but one more death would make it 67%. Check the counts behind every percentage, and merge rare categories (such as several tiny towns into "other") before reading too much into them.

Where machine learning uses contingency tables

  • Categorical features against a categorical target: a crosstab of contract type against churned shows whether a feature is useful before building a model, and which categories differ most.
  • Confusion matrices are contingency tables of actual class against predicted class. Everything here, including row and column percentages, applies to reading them.
  • Leakage and data quality: a feature category where 100% of rows have one target value deserves a check. It may be leaking the answer, or be too rare to trust.
  • Encoding decisions: categories with similar target rates can sometimes be merged, which simplifies one-hot encoding.

Common mistakes

  • Dividing in the wrong direction. Row percentages and column percentages answer different questions.
  • Comparing raw counts across groups of different sizes. Use percentages.
  • Trusting percentages from tiny cells. Look at the counts.
  • Reading a relationship as a cause. Class and survival were linked partly through deck location and lifeboat access; the table can't say which.

Practice

  1. Using the penguin crosstab, what share of Biscoe's penguins are Gentoos? Which normalize setting answers this?
Show the answer

About 74% (124 of 168). It's P(species | island), so normalize="columns" with species as rows.

  1. Predict, then check: what's Cramér's V for Titanic class against deck? Why might it be high?
Show the answer

High: decks were organised by class, with first class on the upper decks.

print(round(association(pd.crosstab(titanic["class"], titanic["deck"])), 3))
0.646

Note that deck is missing for most passengers, so this uses only the rows where it was recorded.

  1. In a table of 1,000 customers, 200 are on a monthly contract and 300 customers churned in total. If contract type and churn were independent, how many monthly-contract customers would churn?
Show the answer

200 × 300 ÷ 1,000 = 60. If the real count is 150, monthly customers churn far more than independence predicts.

  1. Find the survival rate for each embark_town with a crosstab, and say why the result shouldn't be read as "boarding at Cherbourg saved lives".
Show the answer
print(pd.crosstab(titanic["embark_town"], titanic["survived"], normalize="index").round(3))
survived         0      1
embark_town              
Cherbourg    0.446  0.554
Queenstown   0.610  0.390
Southampton  0.663  0.337

Cherbourg passengers survived most often, but more of them were in first class. Class (a confounder, from correlation vs causation) explains much of the gap.

  1. A confusion matrix has actual classes as rows and predicted classes as columns. Which normalize setting gives each class's recall on the diagonal?
Show the answer

normalize="index": each row is divided by the number of actual examples of that class, so the diagonal shows P(predicted correctly | actual class), which is recall.

Interview questions

How do you measure association between two categorical variables?

Build a contingency table, compare observed counts with the counts expected under independence (row total × column total ÷ grand total), and summarise with a chi-square statistic. Cramér's V normalises it to a 0 to 1 strength measure that can be compared across tables; a chi-square test assesses whether the association could be due to chance.

What's the difference between row and column percentages in a crosstab?

Row percentages divide by row totals and give the conditional distribution of the column variable within each row category, P(column | row). Column percentages give P(row | column). They answer different questions, so choose based on which variable you're conditioning on.

Key takeaways

  • A contingency table counts every combination of two categorical columns; pd.crosstab builds it.
  • Row percentages give P(column | row) and column percentages give P(row | column): choose by your question.
  • Expected counts under independence are row total × column total ÷ grand total; big gaps mean a relationship.
  • Cramér's V summarises strength from 0 (independent) to 1 (fully determined).
  • Confusion matrices are contingency tables, and small cells give unreliable percentages.

Frequently asked questions

Can I use correlation on categories by numbering them?

Only for ordered categories (such as ratings 1 to 5), and then Spearman's correlation is the right choice. For unordered categories like islands, numbering them is arbitrary, so any correlation would be meaningless.

What about a category against a number?

Compare the number's distribution within each category: group means or medians, and box plots. For example, body mass by species.

Is Cramér's V the same as the chi-square test?

They use the same chi-square statistic. Cramér's V measures how strong a relationship is; the chi-square test asks whether it could be chance. A tiny relationship can be "significant" in a huge dataset, so look at both.

What to learn next

  1. Revisit numeric relationships in correlation matrix and heatmap in Python.
  2. Read model results as crosstabs in confusion matrix, ROC and AUC.
  3. Review the multiplication rule behind expected counts in independent events explained.