如何解压 scipy ttest_1samp 的结果?

How to unpack the results from scipy ttest_1samp?

Scipy 的 ttest_1samp returns 一个元组,具有 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 的方法来做到这一点。 从此输出中获取浮点数的最佳方法是什么?

来自 the source codescipy.stats.ttest_1samp returns 无非是 namedtuple Ttest_1sampResult 的统计数据和 p 值。因此,您不需要使用 .ravel - 您可以简单地使用

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

访问统计信息。


注: 进一步查看源代码,很明显这个 namedtuple 是从 0.14.0 版本才开始返回的。在 0.13.0 版及更早版本中,似乎 a zero dim array is returned 源代码 ),就所有意图和目的而言,它可以像 BrenBarn 提到的普通数字一样工作。

为了解释@miradulo的回答,如果你使用更新版本的scipy(0.14.0或更高版本),你可以参考返回的[=15=的statistic字段].以这种方式引用是 Pythonic 并且简化了代码,因为不需要记住特定的索引。

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

输出 1.73205080757 0.225403330759

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

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

输出:

The t-statistic is 1.732 and the p-value is 0.225.