【问题标题】:How to unpack the results from scipy ttest_1samp?如何从 scipy ttest_1samp 解压结果?
【发布时间】:2016-04-17 18:03:04
【问题描述】:

Scipy 的 ttest_1samp 返回一个元组,带有 t 统计量和双尾 p 值。

例子:

ttest_1samp([0,1,2], 0) = (array(1.7320508075688774), 0.22540333075851657)

但我只对 t 检验的浮点数(t 统计量)感兴趣,我只能通过使用 [0].ravel()[0] 获得它

例子:

ttest_1samp([0,1,2], 0)[0].ravel()[0] = 1.732

但是,我很确定一定有一种更 Pythonic 的方式来做到这一点。 从此输出中获取浮点数的最佳方法是什么?

【问题讨论】:

  • 你试过ttest_1samp([0,1,2], 0)[0]吗?
  • @BrenBarn 输出array(1.732)
  • 你使用的是什么版本的 numpy/scipy?对我来说,它只返回1.7320508075688774。无论如何,我认为array(1.732) 只是一个零维 numpy 数组,您应该能够在大多数情况下像使用普通数字一样使用它。
  • 差异确实在版本中,我有'0.13.3',得到type(ttest_1samp([0,1,2], 0)[0]) = numpy.ndarray

标签: python scipy tuples iterable-unpacking


【解决方案1】:

为了阐述@miradulo 的回答,如果您使用更新版本的scipy(0.14.0 或更高版本),您可以引用返回的namedtuple 的statistic 字段。以这种方式引用是 Pythonic 并简化了代码,因为不需要记住特定的索引。

代码 res = ttest_1samp(range(3), 0) print(res.statistic) print(res.pvalue)

输出 1.73205080757 0.225403330759

【讨论】:

    【解决方案2】:

    从the source code,scipy.stats.ttest_1samp 仅返回带有统计信息和 p 值的 namedtuple Ttest_1sampResult。因此,您不需要使用 .ravel - 您可以简单地使用

    scipy.stats.ttest_1samp([0,1,2], 0)[0]
    

    访问统计信息。


    注意: 进一步查看源代码,很明显这个 namedtuple 只是在 0.14.0 版本中才开始返回。在 0.13.0 及更早的版本中,a zero dim array is returned(源代码)似乎可以像 BrenBarn 提到的普通数字一样起作用。

    【讨论】:

    • 注意:这个答案是正确的,但是 0.14 及更高版本也值得检查 tdube 的答案,因为它使代码易于阅读
    【解决方案3】:

    您可以通过这种方式获得所需格式的结果:

    print ("The t-statistic is %.3f and the p-value is %.3f." % stats.ttest_1samp([0,1,2], 0))
    

    输出:

    t 统计量为 1.732,p 值为 0.225。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 2020-05-27
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      相关资源
      最近更新 更多