VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/07/t-test-performing-hypothesis-testing-with-python/

⇱ T-Test -Performing Hypothesis Testing With Python - Analytics Vidhya


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Reading list

T-Test -Performing Hypothesis Testing With Python

Lavanya Last Updated : 06 Nov, 2024
5 min read

Introduction

Hi, Enthusiastic readers!

I have a Masters’s degree in Statistics and a year ago, I stepped into the field of data science. Writing a blog was on my bucket list for many days, and here I am making an attempt to share my knowledge.

The main focus of this article is to introduce hypothesis testing and illustrate with a few examples in Python.  Whatever be the concept, its execution can be done easily with programming languages like Python. But, the most important part is drawing inference out of the output and it is highly recommended to know the math behind the executed code.

Hypothesis testing is important in statistics because it gives statistical evidence to show the validity of the study. The null hypothesis states that there is no statistical significance exists between sets of data which implies that the population parameter will be equal to a hypothesized value. Usually, We state the alternative hypothesis which we want to prove. For a null hypothesis H0 and its complementary alternative hypothesis H1, there are 3 cases when the parametric value under H0 ≠ H1 or H0 < H1 or H0 > H1.

Let’s consider a scenario where I have stated the hypothesis, a relevant test statistic, and the Python code for your understanding. I have coded the conclusion part too. Here, I have shared with you few cases instead of covering all. In this blog, I would like to give examples for one sample t-test, two-sample t-test, and paired t-test using Python.

One sample t-test

Data:

Systolic blood pressures of 14 patients are given below:

183, 152, 178, 157, 194, 163, 144, 114, 178, 152, 118, 158, 172, 138

Test, whether the population mean, is less than 165

Hypothesis

H0: There is no significant mean difference in systolic blood pressure. i.e., μ = 165

H1: The population mean is less than 165. i.e., μ < 165

Test statistic  

👁 Image

Where,

x̄ is sample mean

μ is the population mean

s is sample standard deviation

n is the number of observations;

Code

Python Code:

sys_bp=[183, 152, 178, 157, 194, 163, 144, 114, 178, 152, 118, 158, 172, 138]


mu=165


from scipy import stats

t_value,p_value=stats.ttest_1samp(sys_bp,mu)

one_tailed_p_value=float("{:.6f}".format(p_value/2)) # Since alternative hypothesis is one tailed, We need to divide the p value by 2.

print('Test statistic is %f'%float("{:.6f}".format(t_value)))

print('p-value for one tailed test is %f'%one_tailed_p_value)

alpha = 0.05

if one_tailed_p_value<=alpha:
 print('Conclusion','n','Since p value(=%f)'%p_value,'<','alpha(=%.2f)'%alpha,'''We reject the null hypothesis H0. So we conclude that there is no significant mean difference in systolic blood pressure. i.e., μ = 165 at %.2f level of significance'''%alpha)

else:
 print('Conclusion','n','Sincep-value(=%f)'%one_tailed_p_value, '>', 'alpha(=%.2f)'%alpha,'We do not reject the null hypothesis H0.')
So we conclude that there is a significant mean difference in systolic blood pressure.
i.e., μ < 165 at %.2f level of significance”’%alpha)
👁 Image
 

Two sample t-test

Data:

Compare the effectiveness of ammonium chloride and urea, on the grain yield of paddy, an experiment was conducted. The results are given below:

Ammonium

chloride (X1)

13.410.911.211.81415.314.212.61716.216.515.7
Urea (X2)1211.710.711.214.814.413.913.716.91615.616


Hypothesis

H0: The effect of ammonium chloride and urea on grain yield of paddy are equal i.e., μ1 = μ2

H1: The effect of ammonium chloride and urea on grain yield of paddy is not equal i.e., μ1 ≠ μ2

Test statistic

👁 Image


Where,

1 and x̄2 are sample means for x1 and x2 respectively.

n1 and n2 are the numbers of observations in x1 and x2 respectively.

s1 and s2 are the sample standard deviation for x1 and x2 respectively.

Code

Ammonium_chloride=[13.4,10.9,11.2,11.8,14,15.3,14.2,12.6,17,16.2,16.5,15.7]
Urea=[12,11.7,10.7,11.2,14.8,14.4,13.9,13.7,16.9,16,15.6,16]
from scipy import stats

t_value,p_value=stats.ttest_ind(Ammonium_chloride,Urea)

print('Test statistic is %f'%float("{:.6f}".format(t_value)))

print('p-value for two tailed test is %f'%p_value)

alpha = 0.05

if p_value<=alpha:

 print('Conclusion','n','Since p-value(=%f)'%p_value,'<','alpha(=%.2f)'%alpha,'''We reject the null hypothesis H0. So we conclude that the 

effect of ammonium chloride and urea on grain yield of paddy are not equal i.e., μ1 = μ2 at %.2f level of significance.'''%alpha)

else:

 print('Conclusion','n','Since p-value(=%f)'%p_value,'>','alpha(=%.2f)'%alpha,'''We do not reject the null hypothesis H0.
So we conclude that the effect of ammonium chloride and urea on grain yield of paddy are equal
i.e., μ1 ≠ μ2 at %.2f level of significance.”’%alpha)
👁 Image
 

paired t-test

Data:

Eleven schoolboys were given a test in Statistics. They were given a Month’s tuition and a second test were held at the end of it. Do the marks give evidence that the students have benefited from the exam coaching?

Marks in 1st test: 23 20 19 21 18 20 18 17 23 16 19

Marks in 2nd test: 24 19 22 18 20 22 20 20 23 20 18

Hypothesis

H0: The students have not benefited from the tuition class. i.e., d = 0

H1: The students have benefited from the tuition class. i.e., d < 0

Where, d = x-y; d is the difference between marks in the first test (say x) and marks in the second test (say y).

Test statistic

👁 Image

Where, n is the number of samples ‘s’ is sample standard deviation

Code

alpha = 0.05
first_test =[23, 20, 19, 21, 18, 20, 18, 17, 23, 16, 19]
second_test=[24, 19, 22, 18, 20, 22, 20, 20, 23, 20, 18]
from scipy import stats

t_value,p_value=stats.ttest_rel(first_test,second_test)

one_tailed_p_value=float("{:.6f}".format(p_value/2)) 

print('Test statistic is %f'%float("{:.6f}".format(t_value)))

print('p-value for one_tailed_test is %f'%one_tailed_p_value)

alpha = 0.05

if one_tailed_p_value<=alpha:

 print('Conclusion','n','Since p-value(=%f)'%one_tailed_p_value,'<','alpha(=%.2f)'%alpha,'''We reject the null hypothesis H0. 

So we conclude that the students have benefited by the tuition class. i.e., d = 0 at %.2f level of significance.'''%alpha)

else:

 print('Conclusion','n','Since p-value(=%f)'%one_tailed_p_value,'>','alpha(=%.2f)'%alpha,'''We do not reject the null hypothesis H0. 

So we conclude that the students have not benefited by the tuition class. i.e., d = 0 at %.2f level of significance.'''%alpha)
#Output
Test statistic is -1.707331
p-value for one_tailed_test is 0.059282
Conclusion
Since p-value(=0.059282) > alpha(=0.05) We do not reject the null hypothesis H0.
So we conclude that the students have not benefited by the tuition class.
i.e., d = 0 at 0.05 level of significance.
 

 

References:

1. Biostatistics Basic Concepts and Methodology for the Health Sciences By Wayne W. Daniel
2. A Text Book of Agricultural Statistics By Irā Araṅkacāmi, R. Rangaswamy

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Vijayaraja G (mohab)

Good to see our friends going higher and its a proud moment for me to learn from a friend instead of a tutor. Do more.

Amit Patney

In the one tailed 1 sample test the print statement compares p_value with alpha while the if condition has only one tailed p value (pvalue/2) compared with alpha. Why state it that way when that comparison (pvalue vs alpha) was never made?

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
👁 Av Logo White

Continue your learning for FREE

Forgot your password?
👁 Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

👁 Popup Banner
👁 AI Popup Banner