w3resource

Perform Hypothesis testing with NumPy and SciPy's Stats module

NumPy: Integration with SciPy Exercise-7 with Solution

Write a NumPy program to generate random samples and perform a hypothesis test using SciPy's stats module.

Sample Solution:

Python Code:

# Import necessary libraries
import numpy as np
from scipy import stats

# Generate two sets of random samples using NumPy
np.random.seed(0)  # For reproducibility
sample1 = np.random.normal(loc=5, scale=2, size=100)
sample2 = np.random.normal(loc=5.5, scale=2, size=100)

# Perform an independent t-test using SciPy's stats module
t_stat, p_value = stats.ttest_ind(sample1, sample2)

# Print the results of the hypothesis test
print("T-statistic:", t_stat)
print("P-value:", p_value)

Output:

T-statistic: -1.8750754551177837
P-value: 0.06225454602309727

Explanation:

  • Import necessary libraries:
    • Import NumPy for generating random samples and SciPy's stats module for hypothesis testing.
  • Generate two sets of random samples using NumPy:
    • Create two normally distributed samples with different means (loc) but the same standard deviation (scale).
  • Perform an independent t-test using SciPy's stats module:
    • Use ttest_ind to perform a t-test to compare the means of the two samples.
  • Print the results of the hypothesis test:
    • Display the t-statistic and p-value to determine if there is a significant difference between the two samples.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Fit a curve to sample data using NumPy and SciPy's curve_fit.
Next: Ordinary differential equations with NumPy and SciPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/perform-hypothesis-testing-with-numpy-and-scipys-stats-module.php