【问题标题】:Statsmodel Z-test not working as intended (statsmodels.stats.weightstats.CompareMeans.ztest_ind)Statsmodel Z 测试未按预期工作 (statsmodels.stats.weightstats.CompareMeans.ztest_ind)
【发布时间】:2021-03-21 22:57:57
【问题描述】:

一切的格式都像 Statsmodels 网站上一样,但不知何故 Spyder 正在返回:

TypeError: ztest_ind() 为参数 'alternative' 获得了多个值

我的相关输入是这样的(数据框工作正常):

ztest = statsmodels.stats.weightstats.CompareMeans.ztest_ind(df1['TOTAL'], df2['TOTAL'], alternative = 'two-sided', usevar = 'unequal', value = 0)

我正在关注这个网站上的格式:https://www.statsmodels.org/devel/generated/statsmodels.stats.weightstats.CompareMeans.ztest_ind.html

【问题讨论】:

标签: python statsmodels


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多