Contingency tables¶
statsmodels supports a variety of approaches for analyzing contingency tables, including methods for assessing independence, symmetry, homogeneity, and methods for working with collections of tables from a stratified population.
The methods described here are mainly for twoway tables. Multiway
tables can be analyzed using loglinear models. statsmodels does not
currently have a dedicated API for loglinear modeling, but Poisson
regression in statsmodels.genmod.GLM
can be used for this
purpose.
A contingency table is a multiway table that describes a data set in which each observation belongs to one category for each of several variables. For example, if there are two variables, one with \(r\) levels and one with \(c\) levels, then we have a \(r \times c\) contingency table. The table can be described in terms of the number of observations that fall into a given cell of the table, e.g. \(T_{ij}\) is the number of observations that have level \(i\) for the first variable and level \(j\) for the second variable. Note that each variable must have a finite number of levels (or categories), which can be either ordered or unordered. In different contexts, the variables defining the axes of a contingency table may be called categorical variables or factor variables. They may be either nominal (if their levels are unordered) or ordinal (if their levels are ordered).
The underlying population for a contingency table is described by a distribution table \(P_{i, j}\). The elements of \(P\) are probabilities, and the sum of all elements in \(P\) is 1. Methods for analyzing contingency tables use the data in \(T\) to learn about properties of \(P\).
The statsmodels.stats.Table
is the most basic class for
working with contingency tables. We can create a Table
object
directly from any rectangular arraylike object containing the
contingency table cell counts:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: import statsmodels.api as sm
In [4]: df = sm.datasets.get_rdataset("Arthritis", "vcd").data
In [5]: tab = pd.crosstab(df['Treatment'], df['Improved'])
In [6]: tab = tab.loc[:, ["None", "Some", "Marked"]]
In [7]: table = sm.stats.Table(tab)
Alternatively, we can pass the raw data and let the Table class construct the array of cell counts for us:
In [8]: data = df[["Treatment", "Improved"]]
In [9]: table = sm.stats.Table.from_data(data)
Independence¶
Independence is the property that the row and column factors occur independently. Association is the lack of independence. If the joint distribution is independent, it can be written as the outer product of the row and column marginal distributions:
We can obtain the bestfitting independent distribution for our observed data, and then view residuals which identify particular cells that most strongly violate independence:
In [10]: print(table.table_orig) Improved Marked None Some Treatment Placebo 7 29 7 Treated 21 13 7 In [11]: print(table.fittedvalues) Improved Marked None Some Treatment Placebo 14.333333 21.5 7.166667 Treated 13.666667 20.5 6.833333 In [12]: print(table.resid_pearson) Improved Marked None Some Treatment Placebo 1.936992 1.617492 0.062257 Treated 1.983673 1.656473 0.063758
In this example, compared to a sample from a population in which the rows and columns are independent, we have too many observations in the placebo/no improvement and treatment/marked improvement cells, and too few observations in the placebo/marked improvement and treated/no improvement cells. This reflects the apparent benefits of the treatment.
If the rows and columns of a table are unordered (i.e. are nominal factors), then the most common approach for formally assessing independence is using Pearson’s \(\chi^2\) statistic. It’s often useful to look at the cellwise contributions to the \(\chi^2\) statistic to see where the evidence for dependence is coming from.
In [13]: rslt = table.test_nominal_association() In [14]: print(rslt.pvalue) 0.0014626434089526352 In [15]: print(table.chi2_contribs) Improved Marked None Some Treatment Placebo 3.751938 2.616279 0.003876 Treated 3.934959 2.743902 0.004065
For tables with ordered row and column factors, we can us the linear by linear association test to obtain more power against alternative hypotheses that respect the ordering. The test statistic for the linear by linear association test is
where \(r_i\) and \(c_j\) are row and column scores. Often these scores are set to the sequences 0, 1, …. This gives the ‘CochranArmitage trend test’.
In [16]: rslt = table.test_ordinal_association()
In [17]: print(rslt.pvalue)
0.023644578093923983
We can assess the association in a \(r\times x\) table by constructing a series of \(2\times 2\) tables and calculating their odds ratios. There are two ways to do this. The local odds ratios construct \(2\times 2\) tables from adjacent row and column categories.
In [18]: print(table.local_oddsratios)
Improved Marked None Some
Treatment
Placebo 0.149425 2.230769 NaN
Treated NaN NaN NaN
In [19]: taloc = sm.stats.Table2x2(np.asarray([[7, 29], [21, 13]]))
In [20]: print(taloc.oddsratio)
0.14942528735632185
In [21]: taloc = sm.stats.Table2x2(np.asarray([[29, 7], [13, 7]]))
In [22]: print(taloc.oddsratio)
2.230769230769231
The cumulative odds ratios construct \(2\times 2\) tables by dichotomizing the row and column factors at each possible point.
In [23]: print(table.cumulative_oddsratios)
Improved Marked None Some
Treatment
Placebo 0.185185 1.058824 NaN
Treated NaN NaN NaN
In [24]: tab1 = np.asarray([[7, 29 + 7], [21, 13 + 7]])
In [25]: tacum = sm.stats.Table2x2(tab1)
In [26]: print(tacum.oddsratio)
0.18518518518518517
In [27]: tab1 = np.asarray([[7 + 29, 7], [21 + 13, 7]])
In [28]: tacum = sm.stats.Table2x2(tab1)
In [29]: print(tacum.oddsratio)
1.0588235294117647
A mosaic plot is a graphical approach to informally assessing dependence in twoway tables.
In [30]: from statsmodels.graphics.mosaicplot import mosaic
In [31]: fig, _ = mosaic(data, index=["Treatment", "Improved"])
Symmetry and homogeneity¶
Symmetry is the property that \(P_{i, j} = P_{j, i}\) for every \(i\) and \(j\). Homogeneity is the property that the marginal distribution of the row factor and the column factor are identical, meaning that
Note that for these properties to be applicable the table \(P\) (and \(T\)) must be square, and the row and column categories must be identical and must occur in the same order.
To illustrate, we load a data set, create a contingency table, and
calculate the row and column margins. The Table
class
contains methods for analyzing \(r \times c\) contingency tables.
The data set loaded below contains assessments of visual acuity in
people’s left and right eyes. We first load the data and create a
contingency table.
In [32]: df = sm.datasets.get_rdataset("VisualAcuity", "vcd").data
In [33]: df = df.loc[df.gender == "female", :]
In [34]: tab = df.set_index(['left', 'right'])
In [35]: del tab["gender"]
In [36]: tab = tab.unstack()
In [37]: tab.columns = tab.columns.get_level_values(1)
In [38]: print(tab)
right 1 2 3 4
left
1 1520 234 117 36
2 266 1512 362 82
3 124 432 1772 179
4 66 78 205 492
Next we create a SquareTable
object from the contingency
table.
In [39]: sqtab = sm.stats.SquareTable(tab) In [40]: row, col = sqtab.marginal_probabilities In [41]: print(row) right 1 0.255049 2 0.297178 3 0.335295 4 0.112478 dtype: float64 In [42]: print(col) right 1 0.264277 2 0.301725 3 0.328474 4 0.105524 dtype: float64
The summary
method prints results for the symmetry and homogeneity
testing procedures.
In [43]: print(sqtab.summary())
Statistic Pvalue DF

Symmetry 19.107 0.004 6
Homogeneity 11.957 0.008 3

If we had the individual case records in a dataframe called data
,
we could also perform the same analysis by passing the raw data using
the SquareTable.from_data
class method.
sqtab = sm.stats.SquareTable.from_data(data[['left', 'right']])
print(sqtab.summary())
A single 2x2 table¶
Several methods for working with individual 2x2 tables are provided in
the sm.stats.Table2x2
class. The summary
method displays
several measures of association between the rows and columns of the
table.
In [44]: table = np.asarray([[35, 21], [25, 58]])
In [45]: t22 = sm.stats.Table2x2(table)
In [46]: print(t22.summary())
Estimate SE LCB UCB pvalue

Odds ratio 3.867 1.890 7.912 0.000
Log odds ratio 1.352 0.365 0.636 2.068 0.000
Risk ratio 2.075 1.411 3.051 0.000
Log risk ratio 0.730 0.197 0.345 1.115 0.000

Note that the risk ratio is not symmetric so different results will be obtained if the transposed table is analyzed.
In [47]: table = np.asarray([[35, 21], [25, 58]])
In [48]: t22 = sm.stats.Table2x2(table.T)
In [49]: print(t22.summary())
Estimate SE LCB UCB pvalue

Odds ratio 3.867 1.890 7.912 0.000
Log odds ratio 1.352 0.365 0.636 2.068 0.000
Risk ratio 2.194 1.436 3.354 0.000
Log risk ratio 0.786 0.216 0.362 1.210 0.000

Stratified 2x2 tables¶
Stratification occurs when we have a collection of contingency tables
defined by the same row and column factors. In the example below, we
have a collection of 2x2 tables reflecting the joint distribution of
smoking and lung cancer in each of several regions of China. It is
possible that the tables all have a common odds ratio, even while the
marginal probabilities vary among the strata. The ‘BreslowDay’
procedure tests whether the data are consistent with a common odds
ratio. It appears below as the Test of constant OR. The
MantelHaenszel procedure tests whether this common odds ratio is
equal to one. It appears below as the Test of OR=1. It is also
possible to estimate the common odds and risk ratios and obtain
confidence intervals for them. The summary
method displays all of
these results. Individual results can be obtained from the class
methods and attributes.
In [50]: data = sm.datasets.china_smoking.load_pandas()
In [51]: mat = np.asarray(data.data)
In [52]: tables = [np.reshape(x.tolist(), (2, 2)) for x in mat]
In [53]: st = sm.stats.StratifiedTable(tables)
In [54]: print(st.summary())
Estimate LCB UCB

Pooled odds 2.174 1.984 2.383
Pooled log odds 0.777 0.685 0.868
Pooled risk ratio 1.519
Statistic Pvalue

Test of OR=1 280.138 0.000
Test constant OR 5.200 0.636

Number of tables 8
Min n 213
Max n 2900
Avg n 1052
Total n 8419

Module Reference¶

A twoway contingency table. 

Analyses that can be performed on a 2x2 contingency table. 

Methods for analyzing a square contingency table. 

Analyses for a collection of 2x2 contingency tables. 

McNemar test of homogeneity. 

Cochran’s Q test for identical binomial proportions. 
See also¶
Scipy has several functions for analyzing contingency tables, including Fisher’s exact test which is not currently in statsmodels.