Sub topic 13
Discrete data: proportion tests and chi-square
This chapter assumes you can write a null and alternative hypothesis, you know what alpha and a p-value mean, and you have read the test selection map. Here the output (Y) is discrete: each unit is classified as defective or not, passed or failed, late or on time. Averages and standard deviations no longer describe the data. Counts and proportions do.
Why discrete Y needs different tests
A t-test compares means of measurements. With pass/fail data there is no measurement to average. You count how many units fall into each category and compare the resulting proportions, or compare the full pattern of counts across categories.
The tests in this chapter work on counts, so they do not require normality or equal variance. Their assumptions concern sample size and independence of the observations.
| Situation | Y | X | Test |
|---|---|---|---|
| One process against a target rate | Pass/fail | None | One-proportion test (exact binomial) |
| Two groups | Pass/fail | Two categories | Two-proportion z-test or chi-square on a 2x2 table |
| Several groups or several outcome categories | Categories | Categories | Chi-square test of association |
| Small expected counts | Pass/fail | Two categories | Fisher's exact test |
Hypotheses for proportion tests
For a one-proportion test against a target rate of 5% defects:
- H0: the true defect proportion equals 0.05.
- Ha: the true defect proportion is not 0.05. You can use "greater than" if only an increase matters.
For a comparison of two shifts:
- H0: the defect proportion is the same on both shifts.
- Ha: the defect proportions differ.
For a chi-square test of association, the null states that the two classifications are independent. Defect status does not depend on shift. The alternative states that they are associated.
One proportion against a target
Suppose a process must run at a 5% defect rate or better, and a sample of 200 units contains 18 defectives. The sample proportion is 0.09. The exact binomial test asks how surprising 18 or more extreme defects would be if the true rate were 0.05.
from scipy import stats
result = stats.binomtest(k=18, n=200, p=0.05, alternative="two-sided")
print("sample proportion =", 18 / 200)
print("p =", result.pvalue)
print("95% CI =", result.proportion_ci(confidence_level=0.95))Report the confidence interval together with the p-value. The interval shows the plausible range for the true defect rate, and the p-value only says whether the target is inside it.
Two proportions
Now compare two shifts. Shift 1 has 18 defectives in 200 units and shift 2 has 34 in 200. The two-proportion z-test pools the proportions under the null and measures how many standard errors apart the sample proportions are.
from statsmodels.stats.proportion import proportions_ztest
count = [18, 34]
nobs = [200, 200]
z, p = proportions_ztest(count, nobs)
print("z =", z, "p =", p)Here z is about -2.38 and p is about 0.017. At alpha = 0.05 you reject the null: the defect rates differ.
Chi-square test of association
The chi-square test compares the observed counts in a table with the counts you would expect if the two variables were independent. For each cell, the expected count is
(row total x column total) / grand total
The statistic sums (observed - expected)^2 / expected over all cells. A large value means the observed table is far from what independence predicts.
import numpy as np
from scipy import stats
# Rows: shift 1, shift 2. Columns: defective, non-defective.
table = np.array([[18, 182],
[34, 166]])
chi2, p, dof, expected = stats.chi2_contingency(table)
print("chi2 =", chi2, "p =", p, "dof =", dof)
print("Expected counts:\n", expected)The expected counts are 26 and 174 in each row. Degrees of freedom are (rows - 1) x (columns - 1), which is 1 for a 2x2 table.
By default, chi2_contingency applies Yates' continuity correction to 2x2 tables. The statistic is therefore about 4.97 with p of about 0.026, slightly more conservative than the z-test. Without the correction, chi-square equals z squared (5.66), and the two tests agree exactly. Both lead to the same decision here. Pass correction=False if you want to match the z-test.
A table larger than 2x2
The same function handles more rows and columns. Suppose you classify defects by type across three shifts.
import numpy as np
from scipy import stats
# Rows: shifts 1-3. Columns: scratch, dent, misalignment.
table = np.array([[12, 8, 5],
[9, 15, 6],
[10, 7, 14]])
chi2, p, dof, expected = stats.chi2_contingency(table)
print("chi2 =", round(chi2, 2), "p =", round(p, 3), "dof =", dof)
print("Smallest expected count =", expected.min().round(2))A significant result tells you the defect-type mix depends on shift. It does not tell you which cells drive the difference. Look at the cells with the largest (observed - expected)^2 / expected, since those contribute most to the statistic.
Assumptions and the expected-count rule
The chi-square test and the z-test use a normal or chi-square approximation that holds only with enough data. Check these before you trust the p-value:
- Independence. Each unit appears once, and one unit's result does not influence another's. Repeated measures on the same units violate this.
- Expected counts. A common guideline is that every expected count is at least 5. Check the
expectedarray, not the observed counts. A cell with 2 observed defects is fine if 8 were expected. - Random or representative sampling. The sample should reflect the process, not only the units that were easy to inspect.
When expected counts fall below 5 in a 2x2 table, use Fisher's exact test. It computes the exact probability from the hypergeometric distribution and needs no approximation.
import numpy as np
from scipy import stats
small = np.array([[2, 18],
[7, 13]])
odds_ratio, p = stats.fisher_exact(small)
print("odds ratio =", odds_ratio, "p =", p)In this table the expected defective count in the first row is 4.5, which falls below the guideline, so Fisher's test is the appropriate choice. For larger tables with small expected counts, combine sparse categories when that makes sense, or collect more data.
Common errors
- Running a chi-square on percentages. The test needs raw counts. Percentages hide the sample size, which is what drives the p-value.
- Treating a defect count as continuous. If you count defects per unit (0, 1, 2, ...), you have count data that may need a Poisson-based approach. A pass/fail classification per unit is binomial. Decide which one you have before choosing the test.
- Ignoring the direction of a difference. Chi-square says the proportions differ but not which is higher. Always state the sample proportions next to the p-value.
- Reading significance as size. With thousands of units, a difference of 0.2 percentage points can be significant yet worthless. Report the difference in proportions and its confidence interval, and compare it with the change that matters to the project.
- Discretizing a continuous Y. Turning a measurement into pass/fail throws away information and lowers power. Use the discrete test only when the discrete outcome is the thing the project measures, for example when the spec limit defines a defect and no measurement was recorded.
Summary of the workflow
- Confirm Y is a category and X is a category.
- State H0 and Ha in terms of proportions or independence.
- Build the table of raw counts.
- Compute expected counts and check they are at least 5.
- Run the one-proportion, two-proportion, chi-square, or Fisher test.
- Report the sample proportions, the confidence interval, the p-value, and whether the difference matters in practice.
Exercise
A team compares two suppliers. Supplier A has 6 defective parts out of 80, and supplier B has 1 defective part out of 40. Which test should they use for a 2x2 table, and why? Name the check that decides it.
Show answer
Calculate the expected counts. The overall defect rate is 7/120, so the expected defective count is 80 x 7/120 = 4.67 for supplier A and 40 x 7/120 = 2.33 for supplier B. Both are below 5, which breaks the chi-square approximation. Fisher's exact test (scipy.stats.fisher_exact) is the appropriate choice for this 2x2 table.
Exercise
Chi-square on a shift-by-defect-type table gives p = 0.003. Name two things you still need to look at before telling the team what to change.
Show answer
First, find which cells contribute most to the statistic, because the test only says the pattern is associated with shift and does not say where. Second, check the size of the differences in proportions, with confidence intervals, to judge whether they matter in practice. Checking that the expected counts were at least 5 is also acceptable.