api 文档对理解如何使用这个方法帮助不大。
以下是文档中的方法语法(最后提供链接)。
CompareMeans.ztest_ind(alternative='two-sided', usevar='pooled', value=0)
z-test for the null hypothesis of identical means
Parameters
x1array_like, 1-D or 2-D
first of the two independent samples, see notes for 2-D case
x2array_like, 1-D or 2-D
second of the two independent samples, see notes for 2-D case
乍一看,我们没有看到传递用于执行 z 检验的数据值的选项。尽管提到了 2 个参数 x1 和 x2,但在任何地方的方法定义中都没有这些参数的占位符!需要对源代码进行一些挖掘才能弄清楚如何使用它。
所以在源码中(链接在文末提供),ztest_ind()的方法签名也概述了参数x1和x2。
def ztest_ind(self, alternative="two-sided", usevar="pooled", value=0):
"""z-test for the null hypothesis of identical means
Parameters
----------
x1 : array_like, 1-D or 2-D
first of the two independent samples, see notes for 2-D case
x2 : array_like, 1-D or 2-D
second of the two independent samples, see notes for 2-D case
这里最大的提示是“self”参数,它清楚地表明 ztest_ind() 方法必须从具有 2 个类似属性的类对象中调用,即我们希望在其上执行的 2 列数据ztest.
如果我们查看直到 ztest_ind() 的层次结构,我们会发现 ztest_ind() 需要使用 CompareMeans 类的对象引用来调用
statsmodels.stats.weightstats.CompareMeans.ztest_ind
所以我们需要实例化一个 CompareMeans 类的对象。
现在,如果我们转到 CompareMeans() 类签名,它需要 2 个参数,而这些参数又是 DescrStatsW 类的实例!
class CompareMeans(object):
"""class for two sample comparison
The tests and the confidence interval work for multi-endpoint comparison:
If d1 and d2 have the same number of rows, then each column of the data
in d1 is compared with the corresponding column in d2.
Parameters
----------
d1, d2 : instances of DescrStatsW
查看 DescrStatsW 类定义,我们看到它需要一个 1 维或 2 维数组,如数据集。
最后,将所有这些放在一起,我们可以在示例数据集上成功运行 ztest,如下所示!
import statsmodels.stats.weightstats as ws
col1 = ws.DescrStatsW(df1['amount'])
col2 = ws.DescrStatsW(df2['amount'])
cm_obj = ws.CompareMeans(col1, col2)
zstat, z_pval = cm_obj.ztest_ind(usevar='unequal')
print(zstat.round(3), z_pval.round(3)) # --> 2.381 0.017
documentation
source code