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 two-way tables. Multi-way tables can be analyzed using log-linear 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 multi-way 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 array-like 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

ImportErrorTraceback (most recent call last)
<ipython-input-3-085740203b77> in <module>()
----> 1 import statsmodels.api as sm

/builddir/build/BUILD/statsmodels-0.9.0/statsmodels/api.py in <module>()
      5 from . import regression
      6 from .regression.linear_model import OLS, GLS, WLS, GLSAR
----> 7 from .regression.recursive_ls import RecursiveLS
      8 from .regression.quantile_regression import QuantReg
      9 from .regression.mixed_linear_model import MixedLM

/builddir/build/BUILD/statsmodels-0.9.0/statsmodels/regression/recursive_ls.py in <module>()
     14 from statsmodels.regression.linear_model import OLS
     15 from statsmodels.tools.data import _is_using_pandas
---> 16 from statsmodels.tsa.statespace.mlemodel import (
     17     MLEModel, MLEResults, MLEResultsWrapper)
     18 from statsmodels.tools.tools import Bunch

/builddir/build/BUILD/statsmodels-0.9.0/statsmodels/tsa/statespace/mlemodel.py in <module>()
     16 from scipy.stats import norm
     17 
---> 18 from .simulation_smoother import SimulationSmoother
     19 from .kalman_smoother import SmootherResults
     20 from .kalman_filter import (INVERT_UNIVARIATE, SOLVE_LU)

/builddir/build/BUILD/statsmodels-0.9.0/statsmodels/tsa/statespace/simulation_smoother.py in <module>()
      8 
      9 import numpy as np
---> 10 from .kalman_smoother import KalmanSmoother
     11 from . import tools
     12 

/builddir/build/BUILD/statsmodels-0.9.0/statsmodels/tsa/statespace/kalman_smoother.py in <module>()
      9 import numpy as np
     10 
---> 11 from statsmodels.tsa.statespace.representation import OptionWrapper
     12 from statsmodels.tsa.statespace.kalman_filter import (KalmanFilter,
     13                                                       FilterResults)

/builddir/build/BUILD/statsmodels-0.9.0/statsmodels/tsa/statespace/representation.py in <module>()
      8 
      9 import numpy as np
---> 10 from .tools import (
     11     find_best_blas_type, validate_matrix_shape, validate_vector_shape
     12 )

/builddir/build/BUILD/statsmodels-0.9.0/statsmodels/tsa/statespace/tools.py in <module>()
    205             'z': _statespace.zcopy_index_vector
    206         })
--> 207 set_mode(compatibility=None)
    208 
    209 

/builddir/build/BUILD/statsmodels-0.9.0/statsmodels/tsa/statespace/tools.py in set_mode(compatibility)
     57     if not compatibility:
     58         from scipy.linalg import cython_blas
---> 59         from . import (_representation, _kalman_filter, _kalman_smoother,
     60                        _simulation_smoother, _tools)
     61         compatibility_mode = False

ImportError: cannot import name _representation

In [4]: df = sm.datasets.get_rdataset("Arthritis", "vcd").data

NameErrorTraceback (most recent call last)
<ipython-input-4-af5ec03ca238> in <module>()
----> 1 df = sm.datasets.get_rdataset("Arthritis", "vcd").data

NameError: name 'sm' is not defined

In [5]: tab = pd.crosstab(df['Treatment'], df['Improved'])

NameErrorTraceback (most recent call last)
<ipython-input-5-15ac28c3b344> in <module>()
----> 1 tab = pd.crosstab(df['Treatment'], df['Improved'])

NameError: name 'df' is not defined

In [6]: tab = tab.loc[:, ["None", "Some", "Marked"]]

NameErrorTraceback (most recent call last)
<ipython-input-6-35c7697d04d2> in <module>()
----> 1 tab = tab.loc[:, ["None", "Some", "Marked"]]

NameError: name 'tab' is not defined

In [7]: table = sm.stats.Table(tab)

NameErrorTraceback (most recent call last)
<ipython-input-7-c4347556c2e2> in <module>()
----> 1 table = sm.stats.Table(tab)

NameError: name 'sm' is not defined

Alternatively, we can pass the raw data and let the Table class construct the array of cell counts for us:

In [8]: table = sm.stats.Table.from_data(df[["Treatment", "Improved"]])

NameErrorTraceback (most recent call last)
<ipython-input-8-7482675bef59> in <module>()
----> 1 table = sm.stats.Table.from_data(df[["Treatment", "Improved"]])

NameError: name 'sm' is not defined

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:

\[\]

P_{ij} = sum_k P_{ij} cdot sum_k P_{kj} forall i, j

We can obtain the best-fitting independent distribution for our observed data, and then view residuals which identify particular cells that most strongly violate independence:

In [9]: print(table.table_orig)

NameErrorTraceback (most recent call last)
<ipython-input-9-bdebfcd351e6> in <module>()
----> 1 print(table.table_orig)

NameError: name 'table' is not defined

In [10]: print(table.fittedvalues)

NameErrorTraceback (most recent call last)
<ipython-input-10-93e2447e60fa> in <module>()
----> 1 print(table.fittedvalues)

NameError: name 'table' is not defined

In [11]: print(table.resid_pearson)

NameErrorTraceback (most recent call last)
<ipython-input-11-3c1bd716f10e> in <module>()
----> 1 print(table.resid_pearson)

NameError: name 'table' is not defined

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 cell-wise contributions to the \(\chi^2\) statistic to see where the evidence for dependence is coming from.

In [12]: rslt = table.test_nominal_association()

NameErrorTraceback (most recent call last)
<ipython-input-12-2ec3a2583cea> in <module>()
----> 1 rslt = table.test_nominal_association()

NameError: name 'table' is not defined

In [13]: print(rslt.pvalue)

NameErrorTraceback (most recent call last)
<ipython-input-13-f241230dd807> in <module>()
----> 1 print(rslt.pvalue)

NameError: name 'rslt' is not defined

In [14]: print(table.chi2_contribs)

NameErrorTraceback (most recent call last)
<ipython-input-14-f130716672e5> in <module>()
----> 1 print(table.chi2_contribs)

NameError: name 'table' is not defined

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

\[\]

sum_k r_i c_j T_{ij}

where \(r_i\) and \(c_j\) are row and column scores. Often these scores are set to the sequences 0, 1, …. This gives the ‘Cochran-Armitage trend test’.

In [15]: rslt = table.test_ordinal_association()

NameErrorTraceback (most recent call last)
<ipython-input-15-26fa82556e55> in <module>()
----> 1 rslt = table.test_ordinal_association()

NameError: name 'table' is not defined

In [16]: print(rslt.pvalue)

NameErrorTraceback (most recent call last)
<ipython-input-16-f241230dd807> in <module>()
----> 1 print(rslt.pvalue)

NameError: name 'rslt' is not defined

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 [17]: print(table.local_oddsratios)

NameErrorTraceback (most recent call last)
<ipython-input-17-2deb641370f6> in <module>()
----> 1 print(table.local_oddsratios)

NameError: name 'table' is not defined

In [18]: taloc = sm.stats.Table2x2(np.asarray([[7, 29], [21, 13]]))

NameErrorTraceback (most recent call last)
<ipython-input-18-65e07097e026> in <module>()
----> 1 taloc = sm.stats.Table2x2(np.asarray([[7, 29], [21, 13]]))

NameError: name 'sm' is not defined

In [19]: print(taloc.oddsratio)

NameErrorTraceback (most recent call last)
<ipython-input-19-9ccee4e54930> in <module>()
----> 1 print(taloc.oddsratio)

NameError: name 'taloc' is not defined

In [20]: taloc = sm.stats.Table2x2(np.asarray([[29, 7], [13, 7]]))

NameErrorTraceback (most recent call last)
<ipython-input-20-3baf1dbcfc43> in <module>()
----> 1 taloc = sm.stats.Table2x2(np.asarray([[29, 7], [13, 7]]))

NameError: name 'sm' is not defined

In [21]: print(taloc.oddsratio)

NameErrorTraceback (most recent call last)
<ipython-input-21-9ccee4e54930> in <module>()
----> 1 print(taloc.oddsratio)

NameError: name 'taloc' is not defined

The cumulative odds ratios construct \(2\times 2\) tables by dichotomizing the row and column factors at each possible point.

In [22]: print(table.cumulative_oddsratios)

NameErrorTraceback (most recent call last)
<ipython-input-22-c6bac8968cdc> in <module>()
----> 1 print(table.cumulative_oddsratios)

NameError: name 'table' is not defined

In [23]: tab1 = np.asarray([[7, 29 + 7], [21, 13 + 7]])

In [24]: tacum = sm.stats.Table2x2(tab1)

NameErrorTraceback (most recent call last)
<ipython-input-24-5d28bf0ec064> in <module>()
----> 1 tacum = sm.stats.Table2x2(tab1)

NameError: name 'sm' is not defined

In [25]: print(tacum.oddsratio)

NameErrorTraceback (most recent call last)
<ipython-input-25-ff9c4682d78c> in <module>()
----> 1 print(tacum.oddsratio)

NameError: name 'tacum' is not defined

In [26]: tab1 = np.asarray([[7 + 29, 7], [21 + 13, 7]])

In [27]: tacum = sm.stats.Table2x2(tab1)

NameErrorTraceback (most recent call last)
<ipython-input-27-5d28bf0ec064> in <module>()
----> 1 tacum = sm.stats.Table2x2(tab1)

NameError: name 'sm' is not defined

In [28]: print(tacum.oddsratio)

NameErrorTraceback (most recent call last)
<ipython-input-28-ff9c4682d78c> in <module>()
----> 1 print(tacum.oddsratio)

NameError: name 'tacum' is not defined

A mosaic plot is a graphical approach to informally assessing dependence in two-way tables.

from statsmodels.graphics.mosaicplot import mosaic
mosaic(data)

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

\[\]

sum_j P_{ij} = sum_j P_{ji} forall i

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 [29]: df = sm.datasets.get_rdataset("VisualAcuity", "vcd").data

NameErrorTraceback (most recent call last)
<ipython-input-29-bd62c2610a72> in <module>()
----> 1 df = sm.datasets.get_rdataset("VisualAcuity", "vcd").data

NameError: name 'sm' is not defined

In [30]: df = df.loc[df.gender == "female", :]

NameErrorTraceback (most recent call last)
<ipython-input-30-cefa155c8818> in <module>()
----> 1 df = df.loc[df.gender == "female", :]

NameError: name 'df' is not defined

In [31]: tab = df.set_index(['left', 'right'])

NameErrorTraceback (most recent call last)
<ipython-input-31-a9a89cea7be4> in <module>()
----> 1 tab = df.set_index(['left', 'right'])

NameError: name 'df' is not defined

In [32]: del tab["gender"]

NameErrorTraceback (most recent call last)
<ipython-input-32-21569d1674ca> in <module>()
----> 1 del tab["gender"]

NameError: name 'tab' is not defined

In [33]: tab = tab.unstack()

NameErrorTraceback (most recent call last)
<ipython-input-33-333904d786a5> in <module>()
----> 1 tab = tab.unstack()

NameError: name 'tab' is not defined

In [34]: tab.columns = tab.columns.get_level_values(1)

NameErrorTraceback (most recent call last)
<ipython-input-34-63fa72c45fa5> in <module>()
----> 1 tab.columns = tab.columns.get_level_values(1)

NameError: name 'tab' is not defined

In [35]: print(tab)

NameErrorTraceback (most recent call last)
<ipython-input-35-05dd83975d7b> in <module>()
----> 1 print(tab)

NameError: name 'tab' is not defined

Next we create a SquareTable object from the contingency table.

In [36]: sqtab = sm.stats.SquareTable(tab)

NameErrorTraceback (most recent call last)
<ipython-input-36-5f46247189bc> in <module>()
----> 1 sqtab = sm.stats.SquareTable(tab)

NameError: name 'sm' is not defined

In [37]: row, col = sqtab.marginal_probabilities

NameErrorTraceback (most recent call last)
<ipython-input-37-71324058bc5a> in <module>()
----> 1 row, col = sqtab.marginal_probabilities

NameError: name 'sqtab' is not defined

In [38]: print(row)

NameErrorTraceback (most recent call last)
<ipython-input-38-e1bf2d8dc4a4> in <module>()
----> 1 print(row)

NameError: name 'row' is not defined

In [39]: print(col)

NameErrorTraceback (most recent call last)
<ipython-input-39-9a769a44a6f2> in <module>()
----> 1 print(col)

NameError: name 'col' is not defined

The summary method prints results for the symmetry and homogeneity testing procedures.

In [40]: print(sqtab.summary())

NameErrorTraceback (most recent call last)
<ipython-input-40-8d0c6fc13a84> in <module>()
----> 1 print(sqtab.summary())

NameError: name 'sqtab' is not defined

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 [41]: table = np.asarray([[35, 21], [25, 58]])

In [42]: t22 = sm.stats.Table2x2(table)

NameErrorTraceback (most recent call last)
<ipython-input-42-46f9e5d6410f> in <module>()
----> 1 t22 = sm.stats.Table2x2(table)

NameError: name 'sm' is not defined

In [43]: print(t22.summary())

NameErrorTraceback (most recent call last)
<ipython-input-43-49796dcefc62> in <module>()
----> 1 print(t22.summary())

NameError: name 't22' is not defined

Note that the risk ratio is not symmetric so different results will be obtained if the transposed table is analyzed.

In [44]: table = np.asarray([[35, 21], [25, 58]])

In [45]: t22 = sm.stats.Table2x2(table.T)

NameErrorTraceback (most recent call last)
<ipython-input-45-acb5a7b92cf3> in <module>()
----> 1 t22 = sm.stats.Table2x2(table.T)

NameError: name 'sm' is not defined

In [46]: print(t22.summary())

NameErrorTraceback (most recent call last)
<ipython-input-46-49796dcefc62> in <module>()
----> 1 print(t22.summary())

NameError: name 't22' is not defined

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 ‘Breslow-Day’ procedure tests whether the data are consistent with a common odds ratio. It appears below as the Test of constant OR. The Mantel-Haenszel 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 [47]: data = sm.datasets.china_smoking.load()

NameErrorTraceback (most recent call last)
<ipython-input-47-69ece04c2f0e> in <module>()
----> 1 data = sm.datasets.china_smoking.load()

NameError: name 'sm' is not defined

In [48]: mat = np.asarray(data.data)

NameErrorTraceback (most recent call last)
<ipython-input-48-2e22358e427c> in <module>()
----> 1 mat = np.asarray(data.data)

NameError: name 'data' is not defined

In [49]: tables = [np.reshape(x.tolist()[1:], (2, 2)) for x in mat]

NameErrorTraceback (most recent call last)
<ipython-input-49-32cd352cc4f6> in <module>()
----> 1 tables = [np.reshape(x.tolist()[1:], (2, 2)) for x in mat]

NameError: name 'mat' is not defined

In [50]: st = sm.stats.StratifiedTable(tables)

NameErrorTraceback (most recent call last)
<ipython-input-50-60660fbf798b> in <module>()
----> 1 st = sm.stats.StratifiedTable(tables)

NameError: name 'sm' is not defined

In [51]: print(st.summary())

NameErrorTraceback (most recent call last)
<ipython-input-51-ea1038fa2051> in <module>()
----> 1 print(st.summary())

NameError: name 'st' is not defined

Module Reference

Table(table[, shift_zeros]) A two-way contingency table.
Table2x2(table[, shift_zeros]) Analyses that can be performed on a 2x2 contingency table.
SquareTable(table[, shift_zeros]) Methods for analyzing a square contingency table.
StratifiedTable(tables[, shift_zeros]) Analyses for a collection of 2x2 contingency tables.
mcnemar(table[, exact, correction]) McNemar test of homogeneity.
cochrans_q(x[, return_object]) 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.