#NEWLINE# def cochrans_q( x , return_object = True ) : #NEWLINE# #INDENT# "\n    Cochran's Q test for identical binomial proportions.\n\n    Parameters\n    ----------\n    x : array_like, 2d (N, k)\n        data with N cases and k variables\n    return_object : boolean\n        Return values as bunch instead of as individual values.\n\n    Returns\n    -------\n    Returns a bunch containing the following attributes, or the\n    individual values according to the value of `return_object`.\n\n    statistic : float\n       test statistic\n    pvalue : float\n       pvalue from the chisquare distribution\n\n    Notes\n    -----\n    Cochran's Q is a k-sample extension of the McNemar test. If there\n    are only two groups, then Cochran's Q test and the McNemar test\n    are equivalent.\n\n    The procedure tests that the probability of success is the same\n    for every group.  The alternative hypothesis is that at least two\n    groups have a different probability of success.\n\n    In Wikipedia terminology, rows are blocks and columns are\n    treatments.  The number of rows N, should be large for the\n    chisquare distribution to be a good approximation.\n\n    The Null hypothesis of the test is that all treatments have the\n    same effect.\n\n    References\n    ----------\n    http://en.wikipedia.org/wiki/Cochran_test\n    SAS Manual for NPAR TESTS\n    " #NEWLINE# x = np . asarray ( x , dtype = np . float64 ) #NEWLINE# gruni = np . unique ( x ) #NEWLINE# ( N , k ) = x . shape #NEWLINE# count_row_success = ( x == gruni [ ( - 1 ) ] ) . sum ( 1 , float ) #NEWLINE# count_col_success = ( x == gruni [ ( - 1 ) ] ) . sum ( 0 , float ) #NEWLINE# count_row_ss = count_row_success . sum ( ) #NEWLINE# count_col_ss = count_col_success . sum ( ) #NEWLINE# assert ( count_row_ss == count_col_ss ) #NEWLINE# q_stat = ( ( ( gruni - 1 ) * ( ( k * np . sum ( ( count_col_success ** 2 ) ) ) - ( count_col_ss ** 2 ) ) ) / ( ( k * count_row_ss ) - np . sum ( ( count_row_success ** 2 ) ) ) ) #NEWLINE# df = ( k - 1 ) #NEWLINE# pvalue = stats . chi2 . sf ( q_stat , df ) #NEWLINE# if return_object : #NEWLINE# #INDENT# b = _Bunch ( ) #NEWLINE# b . statistic = q_stat #NEWLINE# b . df = df #NEWLINE# b . pvalue = pvalue #NEWLINE# return b #NEWLINE# #UNINDENT# return ( q_stat , pvalue , df )