Skip to Content
ModulesSciPy TutorialStatistics & Testing (stats)

Probability, Statistics & Testing (scipy.stats)

In experimental engineering, physical measurements carry variance, sensor noise, and environmental drift. scipy.stats provides probability distributions, descriptive statistics, and hypothesis tests.


1. The Anatomy of a SciPy Distribution

Every continuous distribution in scipy.stats (e.g. norm, expon, weibull_min) exposes a unified, consistent API:

MethodWhat It Computes
.pdf(x)Probability Density Function f(x)f(x)
.cdf(x)Cumulative Distribution Function P(X≤x)P(X \le x)
.sf(x)Survival Function P(X>x)=1−F(x)P(X > x) = 1 - F(x) (avoids catastrophic cancellation in extreme tails)
.ppf(q)Percent Point Function (Inverse CDF / Quantiles)
.rvs(size)Random variates / samples
.fit(data)Maximum likelihood parameter estimation

Normal Distribution & Statistical Summary


Example

Output:



2. Hypothesis Testing: Welch’s t-test vs Student’s t-test

A hypothesis test calculates how likely the observed data would be if the null hypothesis were true (nothing changed).

📊

What does a p-value mean in plain words?
A p-value is the probability of obtaining test results at least as extreme as the observed data, assuming the null hypothesis is true. A small p-value (p<0.05p < 0.05) indicates the observed difference is unlikely due to random chance alone. It does not prove the alternative hypothesis, nor does it quantify effect magnitude.

Always Use equal_var=False (Welch’s t-test)

Student’s classical t-test assumes both groups share identical variance. If group sizes or variances differ, it suffers severe false-alarm inflation. Welch’s t-test (equal_var=False) is robust and does not assume equal variances:


Example

Output:



3. Non-Parametric Testing & Correlation

When measurement data is skewed, heavily tailed, or ordinal:

Compares medians without assuming normal distributions:

res = stats.mannwhitneyu(group_a, group_b) print(f"U-stat: {res.statistic}, p-value: {res.pvalue:.4f}")

Testing Linear & Rank Correlation


Example

Output:



4. Try It Yourself

Problem: One-Sample t-test

A manufacturing line produces steel pins specified to have mean length μ=100.0 mm\mu = 100.0\text{ mm}. A batch of 12 inspected pins measures: lengths = [100.2, 99.8, 100.5, 100.1, 99.9, 100.4, 100.3, 100.1, 99.7, 100.6, 100.2, 100.0]. Perform a one-sample t-test (ttest_1samp) to test whether the batch mean deviates from 100.0 mm100.0\text{ mm}.

Show solution

from scipy import stats lengths = [100.2, 99.8, 100.5, 100.1, 99.9, 100.4, 100.3, 100.1, 99.7, 100.6, 100.2, 100.0] res = stats.ttest_1samp(lengths, popmean=100.0) print(f"t-statistic: {res.statistic:.4f}") print(f"p-value : {res.pvalue:.4f}")

PygroundTry It Out

Perform a one-sample t-test on pin lengths against popmean 100.0.

Output:

Last updated on