…
…
Statistics and Data Analysis Fundamentals · Lesson 34 / 44 · Inference with formulas
PreviewIn this lesson you will
chi2_contingencyYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
At Bazaar, customer service says "Clothing has a lot of returns," and the product team says "mobile has a lot of returns." Both claims are of the same kind: each says that two categorical variables (category and status, device and status) are related. In this lesson you will test which claim holds in the data with a single test.
So far, every question you tested was about a number: a proportion (the 5% claim), a difference of two proportions (the A/B test), a difference of two means (the delivery time of Arrow Express and Caravan Freight). The question of the two Bazaar teams is different. "Category" takes five values (Electronics, Home & Living, Clothing, Books, Beauty), and "status" takes three (returned, canceled, completed). There is no single difference in proportions; there is a table with five rows and three columns. In this lesson you will learn a tool that tests a whole table like this in one step.
At the end of the lesson you will be able to write a sentence like this:
In this lesson you will:
chi2_contingency.You look at the data before every test. The pd.crosstab you know from lesson 8 counts two categorical columns, and normalize="index" divides each row by its own total to give row proportions. Counts first, then proportions:
import pandas as pd s = pd.read_csv("orders.csv") print(pd.crosstab(s["category"], s["status"])) print(pd.crosstab(s["category"], s["status"], normalize="index").round(3))
Outputstatus canceled completed returned
category
Beauty 9 124 5
Books 7 108 2
Clothing 8 213 45
Electronics 3 148 5
Home & Living 7 194 7
status canceled completed returned
category
Beauty 0.065 0.899 0.036
Books 0.060 0.923 0.017
Clothing 0.030 0.801 0.169
Electronics 0.019 0.949 0.032
Home & Living 0.034 0.933 0.034Why do we look at proportions and not at counts? Because the categories have different sizes: Clothing has 266 orders and Books has 117. Saying "45 returns in Clothing and 2 in Books" is not a fair comparison. You have to divide each category by its own size. In proportions the table says something clear: 16.9% of Clothing orders were returned, against 1.7% to 3.6% in the other four categories. There also seems to be a pattern in cancellations: Books 6.0%, Beauty 6.5%, the others between 2% and 3.5%.
Now look at the product team's claim. In the cell below, change the row_col variable from "category" to "device" and run it:
Try it now· not graded; doesn't affect progress
In the device table, the return rate is 7.9% for mobile and 6.2% for desktop; the cancel rates are 3.7% and 4.1%. There is a difference, but it is small. In which table does the relationship look stronger?
Looking at the row proportions of the category × status and device × status tables, which one shows a stronger relationship between the two variables?
The first step of a test has been the same since lesson 27: if H₀ were true, what would we see? Here H₀ is this: category and status are independent. In other words, which category an order comes from does not change its chance of being returned or canceled. Remember the definition of independence from lesson 24: if A and B are independent, P(A and B) = P(A) × P(B). Put differently, if category does not affect status, the overall proportions apply in every category.
The overall return rate is 64 / 885 = 7.2%. If category did not affect returns, 7.2% of the 266 Clothing orders would be returned:
Expected = row total × column total / grand total = 266 × 64 / 885 = 19.2
The observed value is 45. In Clothing there are more than twice as many returns as we would expect if category did not matter. The same calculation is made for every cell of the table, and the result is an expected table. Its row and column totals are the same as in the observed table; only the numbers are redistributed under the "no relationship" assumption.
Follow the calculation of one cell line by line, and watch the variable boxes:
Run the code line by line: see which line runs next, the variable boxes and the output.
row_total = 266 # Clothing orders col_total = 64 # all returns grand_total = 885 # all orders return_rate = col_total / grand_total expected = row_total * return_rate observed = 45 diff = observed - expected contribution = diff ** 2 / expected print("Overall return rate:", round(return_rate, 3)) print("Expected returns in Clothing:", round(expected, 1)) print("Observed - expected:", round(diff, 1)) print("Contribution of this cell:", round(contribution, 1))
The fourth and fifth lines together are the formula itself: 266 × (64 / 885) = 266 × 64 / 885. We will explain the "contribution" in the last two lines in the next section; for now, notice that this cell produces a large number, 34.5.
You do not need to build the whole expected table by hand. The stats.chi2_contingency function of SciPy takes a table of counts and returns all the parts of the test; the expected table is in the expected_freq field. It is a NumPy array, so we turn it into a DataFrame to put the row and column names back:
import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") table = pd.crosstab(s["category"], s["status"]) r = stats.chi2_contingency(table) expected = pd.DataFrame(r.expected_freq, index=table.index, columns=table.columns) print(expected.round(1)) print("Same row totals?", (expected.sum(axis=1).round(6) == table.sum(axis=1)).all())
Outputstatus canceled completed returned
category
Beauty 5.3 122.7 10.0
Books 4.5 104.0 8.5
Clothing 10.2 236.5 19.2
Electronics 6.0 138.7 11.3
Home & Living 8.0 185.0 15.0
Same row totals? TrueThe expected numbers have decimals: you cannot observe "19.2 returns," but an expected value is a mean, so decimals are natural (like the expected value in lesson 23). In the Clothing row, the observed values are 45 returned, 8 canceled, and 213 completed, and the expected values are 19.2, 10.2, and 236.5. In Books, 2 returns were observed and 8.5 were expected. There are differences everywhere in the table. The question is whether these differences, taken together, can be explained by chance.
Each of the 15 cells has an observed value (O) and an expected value (E). One way to reduce them to a single "distance" number is this: calculate (O − E)² / E for each cell and add them all up. This sum is called the χ² statistic (the Greek letter "chi," pronounced "kai-square"):
χ² = Σ (observed − expected)² / expected
Both parts of the formula do a job. Squaring removes the direction of the difference: too many returns in Clothing and too few in Books both add to the distance; otherwise the pluses and minuses would cancel. Dividing by the expected value scales the difference to the size of the cell: an excess of 5 is very surprising in a cell where 5 is expected, and ordinary in a cell where 236 is expected. Let's see the cell contributions:
import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") table = pd.crosstab(s["category"], s["status"]) r = stats.chi2_contingency(table) contrib = (table - r.expected_freq) ** 2 / r.expected_freq print(contrib.round(2)) print("Sum by hand:", round(contrib.to_numpy().sum(), 2)) print("chi2_contingency:", round(r.statistic, 2), "| df:", r.dof, "| p:", f"{r.pvalue:.2e}")
Outputstatus canceled completed returned
category
Beauty 2.58 0.01 2.48
Books 1.40 0.15 4.93
Clothing 0.48 2.34 34.51
Electronics 1.49 0.62 3.50
Home & Living 0.12 0.44 4.30
Sum by hand: 59.37
chi2_contingency: 59.37 | df: 8 | p: 6.21e-10The sum we made by hand and the statistic field of the function are the same: χ² = 59.37. The Clothing-returned cell alone contributes 34.5, more than half of the total.
Is 59.37 big? Since lesson 27, we have always found the answer in the same way: if H₀ were true, what values would this statistic take? In lesson 29 we shuffled the labels, and we can do the same here. If we shuffle the status column randomly, every link between category and status is broken (H₀ becomes true), but the row and column totals stay the same. Let's calculate χ² for each shuffle:
import numpy as np import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") category = s["category"].to_numpy() status = s["status"].to_numpy() categories = ["Beauty", "Books", "Clothing", "Electronics", "Home & Living"] statuses = ["canceled", "completed", "returned"] def build_table(status_array): table = [] for c in categories: row = [] for st in statuses: row.append(((category == c) & (status_array == st)).sum()) table.append(row) return table rng = np.random.default_rng(42) results = [] for i in range(10_000): shuffled = rng.permutation(status) results.append(stats.chi2_contingency(build_table(shuffled)).statistic) results = np.array(results) print("Mean of the shuffles:", round(results.mean(), 1)) print("Upper end of the middle 95%:", round(np.percentile(results, 95), 1)) print(, (results.(), 1)) (, (results >= 59.37).mean())
OutputMean of the shuffles: 8.0
Upper end of the middle 95%: 15.4
Largest: 30.8
59.37 or above: 0.0(build_table does the same counting as pd.crosstab; it is written with NumPy masks because it is called 10,000 times and this is faster.) If category did not affect status at all, χ² would be around 8 on average. 95% of the shuffles stayed below 15.4, and even the largest of the 10,000 shuffles reached only 30.8. The observed 59.37 is far outside this distribution: p is smaller than 1 in 10,000.
The distribution that the simulation found has a ready-made formula, like the normal curve in lesson 31. Under H₀, the χ² statistic follows the chi-square distribution. This distribution has one setting: the degrees of freedom (df) = (number of rows − 1) × (number of columns − 1). In the category × status table, this is (5 − 1) × (3 − 1) = 8. Why "minus 1"? When the row and column totals are fixed, the last cell in a row can be calculated from the others; the number of cells that can vary freely is 4 × 2 = 8. The mean of the chi-square distribution with df = 8 is exactly 8, and its 95% point is 15.5: almost the same as the 8.0 and 15.4 that we found by simulation. chi2_contingency reads the p-value from this distribution: p = 6.2 × 10⁻¹⁰, that is, 0.00000000062.
The same calculation for the product team's claim:
import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") table = pd.crosstab(s["device"], s["status"]) r = stats.chi2_contingency(table) print(table) print("chi2:", round(r.statistic, 2), "| df:", r.dof, "| p:", round(r.pvalue, 3))
Outputstatus canceled completed returned
device
desktop 15 331 23
mobile 19 456 41
chi2: 1.0 | df: 2 | p: 0.607For device × status, χ² = 1.0, df = (2 − 1) × (3 − 1) = 2, and p = 0.61. If device and status were really independent, a difference this large or larger would appear in about six of every ten data sets. In the language of lesson 28: H₀ cannot be rejected; "there is no evidence of a relationship between device and order status." This does not mean "mobile and desktop are exactly the same"; it means that in 885 orders we cannot tell a difference of this size from chance.
Now try it yourself. The cell below builds the crosstab and runs the test. First run it as it is, then write "device" in place of "category":
Try it now· not graded; doesn't affect progress
The last line of the cell takes you back to lesson 31. The checkout page experiment is also a crosstab: group (A, B) × purchased (0, 1). What happens if we apply chi-square to this 2 × 2 table?
import pandas as pd from scipy import stats from statsmodels.stats.proportion import proportions_ztest o = pd.read_csv("sessions.csv") table = pd.crosstab(o["group"], o["purchased"]) print(table) r = stats.chi2_contingency(table, correction=False) print("chi2 (no correction):", round(r.statistic, 3), "| p:", round(r.pvalue, 4)) z, p = proportions_ztest([40, 65], [500, 500]) print("z:", round(z, 3), "| z²:", round(z ** 2, 3), "| p:", round(p, 4)) r2 = stats.chi2_contingency(table) print("chi2 (default, Yates):", round(r2.statistic, 3), "| p:", round(r2.pvalue, 4))
Outputpurchased 0 1
group
A 435 65
B 460 40
chi2 (no correction): 6.651 | p: 0.0099
z: -2.579 | z²: 6.651 | p: 0.0099
chi2 (default, Yates): 6.129 | p: 0.0133The χ² without correction is 6.651, and the square of the z in lesson 31 is also 6.651; the p-values are the same, 0.0099. Many people think "in a 2 × 2 table, chi-square and the two-proportion test test different things," but this is a misunderstanding: the two are two ways of writing the same test. Chi-square is the two-proportion test extended to more than two rows and columns; z can only compare two groups, while χ² can compare five categories and three statuses at once. Where does the difference in the last line come from? In 2 × 2 tables, chi2_contingency applies a small correction by default (the Yates correction) and gives a slightly more cautious p (0.0133); correction=False turns this correction off. In larger tables there is no correction, and this argument changes nothing.
See three tables side by side. The code keeps the counts ready; the third table is from the customer survey: carrier × satisfied (satisfaction score 4 or 5):
Which table has a relationship? Choose a table and look at χ², df, and p.
Pick a value; predict the output first, then look.
1from scipy import stats2which = "category"3tables = {4 "category": [[9, 124, 5], [7, 108, 2], [8, 213, 45], [3, 148, 5], [7, 194, 7]],5 "device": [[15, 331, 23], [19, 456, 41]],6 "carrier": [[23, 107], [35, 45], [28, 62]],7}8r = stats.chi2_contingency(tables[which])9print("Table:", which)10print("chi2:", round(r.statistic, 2), "| df:", r.dof, "| p:", f"{r.pvalue:.3g}")11print("Smallest expected:", round(r.expected_freq.min(), 1))
Table: category chi2: 59.37 | df: 8 | p: 6.21e-10 Smallest expected: 4.5
Faded lines didn't run with this value. In the category and carrier tables, p is very small: there is a relationship. In the device table, p = 0.607: there is no evidence of a relationship. The df comes from the size of the table: 4 × 2 = 8 in a 5 × 3 table, and 2 in 2 × 3 and 3 × 2 tables. You will use the "Smallest expected" line in the rule of a later section.
The χ² test gives one overall decision: "there is a relationship somewhere in this table." It does not say in which cell. It is wrong to think that "a significant χ² shows that all cells are different"; more than half of 59.37 came from a single cell. To see the source of the relationship, we give each cell its own measure: the standardized residual.
Residual = (observed − expected) / √expected
This is the signed square root of the cell contribution: for Clothing-returned, (45 − 19.2) / √19.2 = 5.87. The sign tells the direction (plus: more than expected, minus: less than expected), and the size tells how surprising it is. Under H₀, residuals behave roughly like a standard normal variable, so they are read like the z-scores in lesson 16: a residual with an absolute value greater than 2 means "this cell is clearly far from what chance would give."
import numpy as np import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") table = pd.crosstab(s["category"], s["status"]) r = stats.chi2_contingency(table) resid = (table - r.expected_freq) / np.sqrt(r.expected_freq) print(resid.round(2))
Outputstatus canceled completed returned
category
Beauty 1.61 0.12 -1.58
Books 1.18 0.39 -2.22
Clothing -0.69 -1.53 5.87
Electronics -1.22 0.79 -1.87
Home & Living -0.35 0.66 -2.07Read this table like a heat map: Clothing-returned shines alone with +5.87. Books-returned (−2.22) and Home & Living-returned (−2.07) are just past the limit, but in the minus direction: these categories have fewer returns than expected. This is the other side of the same Clothing story; because the Clothing returns pull the overall rate up, the other categories look "low" compared with the overall rate. All the other cells are between −1.9 and 1.6. The pattern we saw in cancellations in section 1 (Books and Beauty at 6%) appears in the residuals as 1.18 and 1.61: a little more than expected, but not enough to separate from chance.
You build the result sentence with proportions, not residuals, because the reader does not know residuals: "The return rate is 16.9% in Clothing and between 1.7% and 3.6% in the other categories; category and status are related (χ² = 59.4, df = 8, p < 0.001), and the source of the relationship is the returns in Clothing." The claim of customer service holds in the data.
Match four residual values with their correct interpretation:
What does each value in the category × status residual table say?
For each row, pick its match from the list, then check.
The chi-square test relies on a formula (the chi-square distribution) instead of a simulation, so it depends on conditions, like the normal approximation in lesson 31. There are four rules.
The input must be counts. The test is based on the difference between observed and expected counts. If you give the test the proportion table we looked at in section 1, the function does not give an error, but the result is meaningless: in a percentage table every row adds up to 100, so Books with 117 orders and Clothing with 266 orders look equally heavy, and the total "number of orders" becomes 500, not 885. In the "Common mistake" section at the end of this lesson, you will see how much this changes.
Each unit in one cell. Each order is counted once in the table. If you put a survey question where a customer can choose several categories ("which categories did you shop in?") into a crosstab, the same person enters several cells and the observations are not independent.
Expected counts must not be small. The chi-square distribution is a good approximation when the expected counts are large enough. The common rule: the expected count (not the observed one) of every cell is at least 5. In the category × status table the smallest expected count is 4.5 (Books-canceled): just below the rule, but a deviation this small in a single cell does not change the result; p is in the billionths anyway. If the expected counts are very small, such as 1 or 2, there are two ways: combine categories that make sense together (for example, make two small categories "Other"), or, in 2 × 2 tables, use the Fisher exact test (stats.fisher_exact), which makes no approximation. In lesson 31, when the condition failed, you moved to binomtest; it is the same idea.
The test is the same when groups are chosen in advance. Sometimes the groups of one variable are set by the design (for example 500 / 500 in the A/B test). This is also called a "test of homogeneity"; the calculation and the code are exactly the same.
An analyst gave the chi-square test a percentage table built with pd.crosstab(..., normalize="index") * 100. What happens?
Chi-square works the same way everywhere. A district library tried two entrance layouts: in the old layout new releases were on the back shelves, and in the new layout they were at the entrance. In each layout, they counted whether 50 visitors borrowed a book (fictional sample data):
import pandas as pd from scipy import stats table = pd.DataFrame({"borrowed": [30, 18], "did not borrow": [20, 32]}, index=["old", "new"]) print(table) r = stats.chi2_contingency(table) print("Expected:", r.expected_freq.tolist()) print("With Yates: chi2", round(r.statistic, 2), "| p", round(r.pvalue, 3)) r2 = stats.chi2_contingency(table, correction=False) print("No correction: chi2", round(r2.statistic, 2), "| p", round(r2.pvalue, 3)) print("Borrowing rate: old", 30 / 50, "| new", 18 / 50)
Output borrowed did not borrow
old 30 20
new 18 32
Expected: [[24.0, 26.0], [24.0, 26.0]]
With Yates: chi2 4.85 | p 0.028
No correction: chi2 5.77 | p 0.016
Borrowing rate: old 0.6 | new 0.36In total, 48 people borrowed (48%). If the layout did not matter, 48% of the 50 visitors, that is 24 people, would borrow in both layouts; the expected table is 24 / 26 in each row. The observed values are 30 and 18. The default test (with the Yates correction) gives χ² = 4.85, p = 0.028; without correction, 5.77 and 0.016. Both reach the same decision: shelf layout and borrowing are related. The borrowing rate is 60% in the old layout and 36% in the new one. The expected counts are 24 and 26, so the condition is easily met.
Does this result mean "the new layout reduced borrowing"? In lesson 29, the power of the A/B test came from visitors being assigned to groups at random. Here the library may have used the old layout for one month and the new layout the next month: everything that changes from month to month, such as exam season, holidays, and weather, can also explain the difference. It is wrong to say "chi-square is a cause-and-effect test"; the test only says that two variables change together. Cause and effect come from the design, not from the test.
The library director saw the result (60% borrowing in the old layout, 36% in the new one; χ² = 4.85, p = 0.028) and says, "We are going back to the old layout right now." The old layout was used in October and the new layout in November. What do you suggest?
Pick an option and see what happens. There are no points; you can try the other options too.
With this lesson, the toolbox of the unit is complete: one proportion, two proportions, two means, and two categorical variables. The same thought is under all of them: if H₀ were true, what would we see, and how far is what we saw from it?
In the customer survey, 300 people gave a satisfaction score from 1 to 5 after delivery. Let's count those who gave 4 or 5 as "satisfied" and look at the relationship with the carrier:
import numpy as np import pandas as pd from scipy import stats a = pd.read_csv("survey.csv") a["satisfied"] = a["satisfaction"] >= 4 table = pd.crosstab(a["carrier"], a["satisfied"]) r = stats.chi2_contingency(table) print(pd.crosstab(a["carrier"], a["satisfied"], normalize="index").round(3)) print("chi2", round(r.statistic, 2), "| df", r.dof, "| p", round(r.pvalue, 6)) resid = (table - r.expected_freq) / np.sqrt(r.expected_freq) print(resid.round(2))
Outputsatisfied False True
carrier
Arrow Express 0.177 0.823
Caravan Freight 0.438 0.562
Gull Post 0.311 0.689
chi2 16.82 | df 2 | p 0.000223
satisfied False True
carrier
Arrow Express -2.34 1.48
Caravan Freight 2.52 -1.60
Gull Post 0.43 -0.27The share of satisfied customers is 82.3% for Arrow Express, 68.9% for Gull Post, and 56.2% for Caravan Freight. χ² = 16.82, df = 2, p = 0.0002: carrier and satisfaction are related. The residuals show the two ends: with Caravan Freight there are more unsatisfied customers than expected (+2.52), and with Arrow Express there are fewer than expected (−2.34). Gull Post is close to what is expected. In lesson 32, you found with a t-test that Arrow Express customers were on average 0.53 points more satisfied than Caravan Freight customers; here we look at the same question by splitting the score into two groups, "satisfied or not," and using chi-square, and the result is consistent. But this test also does not say why the carrier affects satisfaction.
Giving the test a percentage table instead of counts. chi2_contingency takes every table to be a table of counts and runs without an error:
import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") percent = pd.crosstab(s["category"], s["status"], normalize="index") * 100 counts = pd.crosstab(s["category"], s["status"]) print("With the percentage table: chi2", round(stats.chi2_contingency(percent).statistic, 2)) print("With counts: chi2", round(stats.chi2_contingency(counts).statistic, 2)) print("Total of the percentage table:", round(percent.to_numpy().sum()), "| real number of orders:", counts.to_numpy().sum())
OutputWith the percentage table: chi2 32.71
With counts: chi2 59.37
Total of the percentage table: 500 | real number of orders: 885The percentage table acts as if there were 100 orders in each of the five categories: the total is 500. The 266 orders of Clothing shrink, the 117 orders of Books grow, and χ² comes out as 32.71 instead of 59.37. If the data were 10 times bigger, the percentages would stay the same and χ² with the percentage table would still be 32.71; with counts it would grow 10 times. Proportions are for reading, counts are for testing.
stats.chi2_contingency(table) gives the statistic, p, df, and expected_freq. Category × status: χ² = 59.4, df = 8, p < 0.001; device × status: χ² = 1.0, p = 0.61.Next lesson: you will look at a question and a type of data and choose which tool of this unit to use.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Let's calculate Cramér's V for the category × status and device × status tables:
import numpy as np import pandas as pd from scipy import stats s = pd.read_csv("orders.csv") for col in ["category", "device"]: table = pd.crosstab(s[col], s["status"]) r = stats.chi2_contingency(table) n = table.to_numpy().sum() v = np.sqrt(r.statistic / (n * (min(table.shape) - 1))) print(col, "| chi2:", round(r.statistic, 2), "| Cramér's V:", round(v, 3))
Outputcategory | chi2: 59.37 | Cramér's V: 0.183
device | chi2: 1.0 | Cramér's V: 0.034V = 0.18: the relationship is real (p < 0.001), but most orders are completed in every category; category explains a part of the status, not all of it. For device, V = 0.03, almost zero.