4

In Python I'm using SciPy for a one sample t test:

from scipy import stats

one_sample_data = [177.3, 182.7, 169.6, 176.3, 180.3, 179.4, 178.5, 177.2, 181.8, 176.5]

one_sample = stats.ttest_1samp(one_sample_data, 175.3)

This is a two tailed test, but I can't see an option in scipy.stats.ttest_1samp to do a one tailed test.

In R if I was using t.test() I would simply set alternative="less" (or "greater"). What's the easiest way to do this in Python?

edc505
  • 871
  • 3
  • 8
  • 14
  • 3
    Take a look https://stackoverflow.com/questions/15984221/how-to-perform-two-sample-one-tailed-t-test-with-numpy-scipy – MishaVacic Jul 06 '17 at 11:16
  • @MishaVacic that answers the question - I thought about flagging duplicate but although the answer is the same, the question is actually a bit different. Do you want to write an answer with the information from the one you linked to? – LangeHaare Jul 18 '17 at 09:49
  • Does this answer your question? [How to perform two-sample one-tailed t-test with numpy/scipy](https://stackoverflow.com/questions/15984221/how-to-perform-two-sample-one-tailed-t-test-with-numpy-scipy) – Travis Feb 05 '20 at 08:45

2 Answers2

4

Based on the link provided in the comments, I would do the following:

from scipy import stats
def one_sample_one_tailed(sample_data, popmean, alpha=0.05, alternative='greater'):
    t, p = stats.ttest_1samp(sample_data, popmean)
    print ('t:',t)
    print ('p:',p)
    if alternative == 'greater' and (p/2 < alpha) and t > 0:
        print ('Reject Null Hypothesis for greater-than test')
    if alternative == 'less' and (p/2 < alpha) and t < 0:
        print ('Reject Null Hypothesis for less-thane test')
sample_data = [177.3, 182.7, 169.6, 176.3, 180.3, 179.4, 178.5, 177.2, 181.8, 176.5]        
one_sample_one_tailed(sample_data,175.3)  

this gives the output:

t: 2.295568968083183
p: 0.04734137339747034
Reject Null Hypothesis for greater-than test

This solution is based on the accepted answer in the link:

It goes on to say that scipy always gives the test statistic as signed. This means that given p and t values from a two-tailed test, you would reject the null hypothesis of a greater-than test when p/2 < alpha and t > 0, and of a less-than test when p/2 < alpha and t < 0.

Nikhil Talreja
  • 2,754
  • 1
  • 14
  • 20
1

Now 'alternative' parameter available with the newest version of Scipy (>=1.6) Here is the link :

https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_1samp.html