Categorical association in Python
A contingency table, a chi-square test, and Fisher's exact for small counts.
import numpy as np
from scipy import stats
table = np.array([[30, 10], [18, 22]])
result = stats.chi2_contingency(table)
print(round(result.statistic, 3), f"{result.pvalue:.5f}", result.dof)
print(result.expected_freq.round(1))
small = np.array([[8, 2], [1, 5]])
odds, p = stats.fisher_exact(small)
print(round(odds, 3), round(p, 5))
How it works
chi2_contingencyreturns the statistic, p, dof and expected counts.- The expected table is what the test compares against.
fisher_exactis right when any expected count is tiny.
Keywords and builtins used here
asprintround
The run, in numbers
- Lines
- 12
- Characters to type
- 336
- Tokens
- 119
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 68 seconds.
Step 3 of 4 in Hypothesis tests, step 6 of 23 in Scientific computing with SciPy.