Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack the results from scipy ttest_1samp?

Scipy's ttest_1samp returns a tuple, with the t-statistic, and the two-tailed p-value.

Example:

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

But I'm only interested in the float of the t-test (the t-statistic), which I have only been able to get by using [0].ravel()[0]

Example:

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

However, I'm quite sure there must be a more pythonic way to do this. What is the best way to get the float from this output?

like image 297
sapo_cosmico Avatar asked Oct 22 '25 02:10

sapo_cosmico


2 Answers

To expound on @miradulo's answer, if you use a newer version of scipy (release 0.14.0 or later), you can reference the statistic field of the returned namedtuple. Referencing this way is Pythonic and simplifies the code as there is no need to remember specific indices.

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

Output 1.73205080757 0.225403330759

like image 176
tdube Avatar answered Oct 23 '25 16:10

tdube


From the source code, scipy.stats.ttest_1samp returns nothing more than a namedtuple Ttest_1sampResult with the statistic and p-value. Hence, you do not need to use .ravel - you can simply use

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

to access the statistic.


Note: From a further look at the source code, it is clear that this namedtuple only began being returned in release 0.14.0. In release 0.13.0 and earlier, it appears that a zero dim array is returned (source code), which for all intents and purposes can act just like a plain number as mentioned by BrenBarn.

like image 36
miradulo Avatar answered Oct 23 '25 16:10

miradulo