SciPy Probability Distributions
A probability distribution describes how likely each possible value of a random quantity is: the heights of adults, the number of emails arriving per hour, the lifetime of a light bulb. scipy.stats contains more than 100 distributions, and they all share the same interface, so once you learn it for one you know it for all.
Continuous distributions
The normal (Gaussian) distribution is the classic bell curve, defined by a mean loc and a standard deviation scale. You can call methods directly on stats.norm, passing the parameters each time, or freeze a distribution with fixed parameters:
from scipy import stats
heights = stats.norm(loc=170, scale=8) # a "frozen" distribution
print("mean, std :", heights.mean(), heights.std())
print("pdf(170) :", round(heights.pdf(170), 5))
print("P(H < 180) :", round(heights.cdf(180), 4))
print("P(H > 190) :", round(heights.sf(190), 4))
print("median :", heights.ppf(0.5))
print("90th pct :", round(heights.ppf(0.9), 2))
print("middle 95% :", [round(float(v), 2) for v in heights.interval(0.95)])mean, std : 170.0 8.0
pdf(170) : 0.04987
P(H < 180) : 0.8944
P(H > 190) : 0.0062
median : 170.0
90th pct : 180.25
middle 95% : [154.32, 185.68]
The common methods are:
| Method | Name | Answers |
|---|---|---|
pdf(x) |
probability density function | How dense is probability around x? |
cdf(x) |
cumulative distribution function | P(X ≤ x) |
sf(x) |
survival function, 1 - cdf |
P(X > x) |
ppf(q) |
percent-point function (inverse cdf) | Which x has P(X ≤ x) = q? |
rvs(size, random_state) |
random variates | Draw random samples |
mean(), std(), var(), median() |
moments | Summary values |
interval(c) |
central interval | Range holding the middle c share |
fit(data) |
parameter estimation | Best parameters for some data |
For discrete distributions, pdf is replaced by pmf (probability mass function).
Discrete distributions
The binomial distribution counts successes in a fixed number of independent tries; the Poisson distribution counts events in a fixed interval when they happen at a known average rate:
from scipy import stats
# 10 free throws, each made with probability 0.7
shots = stats.binom(n=10, p=0.7)
print("P(exactly 7) :", round(shots.pmf(7), 4))
print("P(at most 5) :", round(shots.cdf(5), 4))
print("expected :", shots.mean())
# A help desk gets 4 calls per hour on average
calls = stats.poisson(mu=4)
for k in range(0, 9, 2):
print(f"P({k} calls) : {calls.pmf(k):.4f}")
print("P(> 8 calls) :", round(calls.sf(8), 4))P(exactly 7) : 0.2668
P(at most 5) : 0.1503
expected : 7.0
P(0 calls) : 0.0183
P(2 calls) : 0.1465
P(4 calls) : 0.1954
P(6 calls) : 0.1042
P(8 calls) : 0.0298
P(> 8 calls) : 0.0214
Drawing random samples
Use rvs() with a seeded generator to simulate data reproducibly:
import numpy as np
from scipy import stats
rng = np.random.default_rng(42)
waits = stats.expon(scale=5).rvs(size=10_000, random_state=rng) # waits with mean 5 min
print("sample mean :", round(waits.mean(), 3))
print("sample std :", round(waits.std(), 3))
print("share > 10 :", round((waits > 10).mean(), 4))
print("theory > 10 :", round(stats.expon(scale=5).sf(10), 4))sample mean : 4.944
sample std : 4.962
share > 10 : 0.1332
theory > 10 : 0.1353
With 10 000 samples, the simulated share of waits over 10 minutes is close to the exact value from the survival function.
Plotting densities
Different distributions have very different shapes. Here are four common ones, each evaluated with pdf on a grid:
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
x = np.linspace(0, 10, 300)
dists = {
"normal(5, 1.5)": stats.norm(5, 1.5),
"gamma(a=2, scale=1.5)": stats.gamma(a=2, scale=1.5),
"lognorm(s=0.5, scale=3)": stats.lognorm(s=0.5, scale=3),
"uniform(loc=2, scale=6)": stats.uniform(loc=2, scale=6),
}
for label, d in dists.items():
plt.plot(x, d.pdf(x), label=label)
plt.legend()
plt.title("Probability density functions")
plt.show()
for label, d in dists.items():
print(f"{label:24} mean={d.mean():.2f} std={d.std():.2f}")normal(5, 1.5) mean=5.00 std=1.50
gamma(a=2, scale=1.5) mean=3.00 std=2.12
lognorm(s=0.5, scale=3) mean=3.40 std=1.81
uniform(loc=2, scale=6) mean=5.00 std=1.73
Note how uniform(loc, scale) covers the range [loc, loc + scale] — every SciPy distribution uses loc to shift and scale to stretch.
Fitting a distribution to data
fit() estimates the parameters that best explain some data (by maximum likelihood). Here we simulate component lifetimes from a Weibull distribution and recover its parameters:
import numpy as np
from scipy import stats
rng = np.random.default_rng(1)
lifetimes = stats.weibull_min(c=1.8, scale=1000).rvs(size=2000, random_state=rng)
c, loc, scale = stats.weibull_min.fit(lifetimes, floc=0) # fix loc at 0
print(f"shape c = {c:.3f} (true 1.8)")
print(f"scale = {scale:.1f} (true 1000)")
fitted = stats.weibull_min(c, loc, scale)
print(f"P(fails before 500 h) = {fitted.cdf(500):.3f}")shape c = 1.819 (true 1.8)
scale = 1003.6 (true 1000)
P(fails before 500 h) = 0.245
Tip: Fixing parameters you already know (
floc=0,fscale=1) makes fitting faster and more reliable. Many distributions in SciPy have alocparameter that you'd normally want at zero.
Test yourself
Which method answers 'what is P(X ≤ x)?'
- cdf
- ppf
- rvs
What does stats.norm(170, 8).ppf(0.9) return?
- The probability that a value is below 0.9
- The value below which 90% of the distribution lies
- The density at 0.9
- A random sample
For discrete distributions like binom, which method replaces pdf?
- pmf
- cdf
- dmf
- sf