Chisquare test of independence of variables in a contingency table.
This function computes the chisquare statistic and pvalue for the hypothesis test of independence of the observed frequencies in the contingency table [R77] observed. The expected frequencies are computed based on the marginal sums under the assumption of independence; see scipy.stats.expected_freq. The number of degrees of freedom is (expressed using numpy functions and attributes):
dof = observed.size  sum(observed.shape) + observed.ndim  1
Parameters :  observed : array_like
correction : bool, optional


Returns :  chi2 : float
p : float
dof : int
expected : ndarray, same shape as observed

See also
Notes
An often quoted guideline for the validity of this calculation is that the test should be used only if the observed and expected frequency in each cell is at least 5.
This is a test for the independence of different categories of a population. The test is only meaningful when the dimension of observed is two or more. Applying the test to a onedimensional table will always result in expected equal to observed and a chisquare statistic equal to 0.
This function does not handle masked arrays, because the calculation does not make sense with missing values.
Like stats.chisquare, this function computes a chisquare statistic; the convenience this function provides is to figure out the expected frequencies and degrees of freedom from the given contingency table. If these were already known, and if the Yates’ correction was not required, one could use stats.chisquare. That is, if one calls:
chi2, p, dof, ex = chi2_contingency(obs, correction=False)
then the following is true:
(chi2, p) == stats.chisquare(obs.ravel(), f_exp=ex.ravel(),
ddof=obs.size  1  dof)
References
[R77]  (1, 2) http://en.wikipedia.org/wiki/Contingency_table 
Examples
A twoway example (2 x 3):
>>> obs = np.array([[10, 10, 20], [20, 20, 20]])
>>> chi2_contingency(obs)
(2.7777777777777777,
0.24935220877729619,
2,
array([[ 12., 12., 16.],
[ 18., 18., 24.]]))
A fourway example (2 x 2 x 2 x 2):
>>> obs = np.array(
... [[[[12, 17],
... [11, 16]],
... [[11, 12],
... [15, 16]]],
... [[[23, 15],
... [30, 22]],
... [[14, 17],
... [15, 16]]]])
>>> chi2_contingency(obs)
(8.7584514426741897,
0.64417725029295503,
11,
array([[[[ 14.15462386, 14.15462386],
[ 16.49423111, 16.49423111]],
[[ 11.2461395 , 11.2461395 ],
[ 13.10500554, 13.10500554]]],
[[[ 19.5591166 , 19.5591166 ],
[ 22.79202844, 22.79202844]],
[[ 15.54012004, 15.54012004],
[ 18.10873492, 18.10873492]]]]))