scipy.stats holds probability distributions, statistical tests and resampling tools. This page covers the distribution API, a test-selection table, effect sizes, confidence intervals, bootstrap and permutation_test. The examples use the checkout A/B test in data/ab_test.csv and the house sales in data/houses.csv. The blocks share one session:
ab = pd.read_csv( "data/ab_test.csv" )
houses = pd.read_csv( "data/houses.csv" )
is_t = ab[ "group" ] == "treatment"
t_time = ab.loc[is_t, "time_on_page_s" ].to_numpy() # seconds on the page
c_time = ab.loc[ ~ is_t, "time_on_page_s" ].to_numpy()
buyers = ab[ab[ "converted" ] == 1 ]
rev = buyers[ "revenue" ].to_numpy() # order value of buyers
I want to…
Use…
Notes
a distribution with fixed parameters
d = stats.norm(loc=m, scale=s)
a “frozen” distribution
P(X ≤ x)
d.cdf(x)
discrete and continuous
P(X > x)
d.sf(x)
more precise than 1 - cdf in the tail
P(a < X ≤ b)
d.cdf(b) - d.cdf(a)
P(X = k), discrete
d.pmf(k)
pdf is a density, not a probability
P(X ≥ k), discrete
d.sf(k - 1)
sf(k) is P(X > k)
the value at a quantile
d.ppf(q)
inverse of cdf
a central range with 95% probability
d.interval(0.95)
repeatable random draws
d.rvs(size=n, random_state=42)
or a Generator
fit a distribution to data
stats.lognorm.fit(x, floc=0)
returns a tuple of parameters
check a fitted distribution
stats.goodness_of_fit(dist, x, rng=rng)
Monte Carlo p-value
compare a mean with a target
stats.ttest_1samp(x, popmean=m)
compare two group means
stats.ttest_ind(a, b, equal_var=False)
Welch; the default is Student
compare paired measurements
stats.ttest_rel(after, before)
or stats.wilcoxon
compare two skewed groups
stats.mannwhitneyu(a, b)
ranks
compare 3+ group means
stats.f_oneway(*groups, equal_var=False)
Welch ANOVA
compare 3+ skewed groups
stats.kruskal(*groups)
find which pairs differ
stats.tukey_hsd(*groups)
after ANOVA
test two categorical variables
stats.chi2_contingency(table)
table = pd.crosstab(a, b)
test counts against expected shares
stats.chisquare(obs, f_exp=exp)
sample ratio mismatch
test a small 2×2 table
stats.fisher_exact(table)
exact
test one proportion
stats.binomtest(k, n, p=0.5)
.proportion_ci()
a correlation with a p-value
stats.pearsonr(x, y), stats.spearmanr(x, y)
.confidence_interval() on Pearson
compare two whole distributions
stats.ks_2samp(a, b)
check normality
stats.probplot(x) (Q-Q), stats.shapiro(x)
prefer the plot
check equal variances
stats.levene(a, b)
a CI for a mean
stats.t.interval(0.95, n - 1, loc=m, scale=stats.sem(x))
a CI for a difference of means
stats.ttest_ind(...).confidence_interval()
a CI for any statistic
stats.bootstrap((x,), np.median, rng=rng)
BCa by default
a p-value for any statistic
stats.permutation_test((a, b), stat, rng=rng)
no distribution assumption
Cramér’s V
stats.contingency.association(table)
an odds ratio with a CI
stats.contingency.odds_ratio(table)
a relative risk with a CI
stats.contingency.relative_risk(k1, n1, k2, n2)
adjust many p-values
stats.false_discovery_control(p)
Benjamini–Hochberg
standard error, IQR, z-scores
stats.sem(x), stats.iqr(x), stats.zscore(x)
Method
Gives
Note
pdf(x) / pmf(k)
density (continuous) / P(X = k) (discrete)
logpdf, logpmf for tiny values
cdf(x)
P(X ≤ x)
logcdf
sf(x)
P(X > x) = 1 − cdf
survival function
ppf(q)
the x with cdf(x) = q
“percent point function” (quantile)
isf(q)
the x with sf(x) = q
upper critical values: stats.norm.isf(0.025)
interval(c)
the central range with probability c
mean(), median(), var(), std()
moments
stats(moments="mvsk")
mean, variance, skew, excess kurtosis
expect(func)
E[func(X)]
numerical integral or sum
support()
the range of possible values
rvs(size, random_state)
random draws
fit(data)
parameter estimates (MLE)
only on the unfrozen class
Every method also works unfrozen, with the parameters as arguments: stats.norm.cdf(x, loc=m, scale=s). Freeze a distribution when you call it more than once.
Distribution
scipy
Parameters → meaning
Use for
normal
stats.norm(loc, scale)
mean, sd
measurement noise, sums
t
stats.t(df, loc, scale)
degrees of freedom
small-sample means
chi-square
stats.chi2(df)
variance tests, contingency tables
F
stats.f(dfn, dfd)
ANOVA
uniform
stats.uniform(loc=a, scale=b - a)
width , not the upper end
exponential
stats.expon(scale=1 / lam)
scale = 1/rate
waiting times
gamma
stats.gamma(a, scale=theta)
shape, scale
positive skewed values
log-normal
stats.lognorm(s=sigma, scale=np.exp(mu))
sd and exp(mean) of the log
money, sizes
beta
stats.beta(a, b)
rates and proportions in 0–1
Weibull
stats.weibull_min(c, scale)
shape, scale
lifetimes
binomial
stats.binom(n, p)
trials, success probability
k successes in n trials
Poisson
stats.poisson(mu)
rate per interval
counts of events
geometric
stats.geom(p)
trials up to the first success; starts at 1
negative binomial
stats.nbinom(n, p)
overdispersed counts; failures before n successes
hypergeometric
stats.hypergeom(M, n, N)
population, successes in it, draws
draws without replacement
d = stats.norm( loc = 87 , scale = 40 ) # frozen: time on page, roughly
print ( round (d.cdf( 120 ), 4 ), round (d.sf( 120 ), 4 )) # P(X <= 120), P(X > 120)
print (d.ppf([ 0.05 , 0.5 , 0.95 ]).round( 1 ), np.round(d.interval( 0.9 ), 1 ))
print ( round (stats.norm.cdf( 120 , loc = 87 , scale = 40 ), 4 )) # the same, unfrozen
b = stats.binom( n = 20 , p = 0.11 ) # 20 visitors, 11% convert
print ( round (b.pmf( 2 ), 4 ), round (b.cdf( 2 ), 4 ), round (b.sf( 4 ), 4 )) # sf(4) = P(X >= 5)
print ( round (stats.expon( scale = 1 / 3 ).mean(), 4 )) # rate 3 per hour -> 20 minutes
print (d.rvs( size = 3 , random_state = 42 ).round( 1 ))
print ( round (stats.norm.isf( 0.025 ), 3 ), round (stats.t( df = 9 ).isf( 0.025 ), 3 )) # 2-sided 5%
[ 21.2 87. 152.8] [ 21.2 152.8]
s, loc, scale = stats.lognorm.fit(rev, floc = 0 ) # floc=0: the usual 2-parameter fit
print ( round (s, 3 ), round (np.log(scale), 3 )) # sigma and mu of log(revenue)
print ( round (np.log(rev).std(), 3 ), round (np.log(rev).mean(), 3 )) # the same by hand
fitted = stats.lognorm(s, loc = 0 , scale = scale)
print ( round (fitted.sf( 100 ), 4 ), round ((rev > 100 ).mean(), 4 )) # model tail vs data
gof = stats.goodness_of_fit(
stats.lognorm, rev, known_params = { "loc" : 0 }, rng = np.random.default_rng( 42 )
print ( round (gof.statistic, 3 ), round (gof.pvalue, 3 )) # large p: no evidence of misfit
Fitting tool
Does
Watch out
dist.fit(x)
MLE of all parameters
fix known ones: floc=0, fscale=1, f0=...
stats.fit(dist, x, bounds=...)
MLE with bounds; returns FitResult
without bounds for loc and scale, they stay at 0 and 1
stats.goodness_of_fit(dist, x)
KS/AD test with the parameters re-fitted on each Monte Carlo sample
slow on large data; pass rng
stats.kstest(x, "norm", args=(m, s))
KS test against known parameters
with parameters fitted on x, the p-value is far too large
stats.probplot(x, dist=stats.lognorm(s))
Q-Q plot data and fit r
plot=ax draws it
SciPy 1.15+ adds classes such as stats.Normal(mu=0, sigma=1) and stats.Uniform(a=0, b=1). Their methods have new names: icdf instead of ppf, ccdf instead of sf, sample(n, rng=rng) instead of rvs. stats.make_distribution(stats.gamma) turns a classic distribution into a class of this kind. The classic stats.norm API stays and is what most code uses.
Test
When
Function
Assumptions
one-sample t
one mean vs a target
ttest_1samp(x, popmean=m)
independent values; mean close to normal (CLT)
Welch t
two independent means
ttest_ind(a, b, equal_var=False)
independent groups; no equal variances needed
Student t
two means, equal variances
ttest_ind(a, b)
equal variances; rarely worth the risk
paired t
before/after on the same units
ttest_rel(after, before)
differences close to normal
Mann–Whitney U
two independent groups, skewed or ordinal
mannwhitneyu(a, b)
tests P(A > B) = 0.5, not medians
Brunner–Munzel
like Mann–Whitney with unequal spreads
brunnermunzel(a, b)
no equal-spread assumption
Wilcoxon signed-rank
paired or one-sample, skewed
wilcoxon(after, before)
symmetric differences
one-way ANOVA
3+ means
f_oneway(*g) (equal_var=False: Welch)
normal-ish groups
Kruskal–Wallis
3+ skewed groups
kruskal(*g)
independent groups; similar shapes only if you read it as a median test
Tukey HSD
all pairs after ANOVA
tukey_hsd(*g)
equal variances; else equal_var=False
Friedman
3+ paired conditions
friedmanchisquare(a, b, c)
blocks of related values
chi-square independence
two categorical variables
chi2_contingency(table)
expected counts ≥ 5
chi-square goodness of fit
counts vs expected shares
chisquare(obs, f_exp=exp)
sums of obs and f_exp match
Fisher exact
small 2×2 table
fisher_exact(table)
fixed margins
Barnard / Boschloo
small 2×2 table, more power
barnard_exact(t), boschloo_exact(t)
slow for large counts
binomial
one proportion vs p
binomtest(k, n, p)
independent trials
Pearson
linear association
pearsonr(x, y)
linear; outliers distort it
Spearman / Kendall
monotonic association
spearmanr(x, y), kendalltau(x, y)
ranks
KS two-sample
any difference in distribution
ks_2samp(a, b)
continuous data
Shapiro–Wilk
normality
shapiro(x)
too sensitive at large n
Levene
equal variances
levene(a, b)
robust to non-normality
permutation
any statistic, few assumptions
permutation_test(data, stat)
exchangeable under H0
Member
Gives
res.statistic, res.pvalue
on every test result; also unpacks: t, p = res
res.df
degrees of freedom (t-tests; res.dof for chi2_contingency)
res.confidence_interval(0.95)
t-tests, pearsonr, binomtest (proportion_ci), odds_ratio
res.expected_freq
expected counts of chi2_contingency
alternative="less" / "greater"
one-sided H1 about the first argument, decided in advance
nan_policy="omit"
drop NaN instead of returning nan
axis=0
test every column of a 2-D array at once
print ( f "Welch t: p = { stats.ttest_ind(t_time, c_time, equal_var = False ).pvalue :.1e } " )
res = stats.ttest_ind(t_time, c_time, equal_var = False )
print (np.round(res.confidence_interval(), 2 ), round (res.df, 1 )) # CI of t - c
t_rev = buyers.loc[buyers[ "group" ] == "treatment" , "revenue" ]
c_rev = buyers.loc[buyers[ "group" ] == "control" , "revenue" ]
print ( f "Mann-Whitney p = { stats.mannwhitneyu(t_rev, c_rev).pvalue :.3f } " )
table = pd.crosstab(ab[ "group" ], ab[ "converted" ])
chi = stats.chi2_contingency(table) # Yates' correction on 2x2 by default
print ( f "chi2 = { chi.statistic :.2f } , dof = { chi.dof } , p = { chi.pvalue :.4f } " )
srm = stats.chisquare(ab[ "group" ].value_counts()) # expected: a 50/50 split
print ( f "SRM p = { srm.pvalue :.3f } " )
by_device = [g.to_numpy() for _, g in ab.groupby( "device" )[ "time_on_page_s" ]]
print ( f "Welch ANOVA p = { stats.f_oneway( * by_device, equal_var = False ).pvalue :.1e } " )
print ( f "Kruskal p = { stats.kruskal( * by_device).pvalue :.1e } " )
chi2 = 6.02, dof = 1, p = 0.0141
before = np.array([ 12.1 , 9.8 , 11.4 , 13.0 , 10.2 , 12.7 , 9.5 , 11.9 ]) # same 8 users
after = np.array([ 11.0 , 9.9 , 10.1 , 12.2 , 9.0 , 12.5 , 8.7 , 11.1 ])
print ( round (stats.ttest_rel(after, before).pvalue, 4 )) # paired: test the differences
print ( round (stats.wilcoxon(after, before).pvalue, 4 )) # rank version
print ( round (stats.ttest_ind(after, before).pvalue, 4 )) # wrong: ignores the pairing
x, y = np.log(houses[ "sqft" ]), np.log(houses[ "price" ])
print ( round (r.statistic, 3 ), np.round(r.confidence_interval(), 3 ))
print ( round (stats.spearmanr(houses[ "sqft" ], houses[ "price" ]).statistic, 3 ))
p = np.array([ 0.001 , 0.008 , 0.039 , 0.041 , 0.042 , 0.060 , 0.074 , 0.205 ])
print (np.round(stats.false_discovery_control(p), 3 )) # BH-adjusted p-values
print ((stats.false_discovery_control(p) <= 0.05 ).sum(), (p * len (p) <= 0.05 ).sum())
[0.008 0.032 0.067 0.067 0.067 0.08 0.085 0.205]
The second line counts the discoveries at 5%: Benjamini–Hochberg finds 2, Bonferroni (p × m) finds 1.
A p-value says whether an effect is distinguishable from noise. An effect size says how large it is. Report both.
Effect size
Formula or code
Rough scale
difference of means
a.mean() - b.mean() with its CI
in the units of the data
Cohen’s d
( x ˉ 1 − x ˉ 2 ) / s p (\bar{x}_1 - \bar{x}_2) / s_p ( x ˉ 1 − x ˉ 2 ) / s p
0.2 small, 0.5 medium, 0.8 large
Hedges’ g
d × ( 1 − 3 / ( 4 ( n 1 + n 2 ) − 9 ) ) d \times (1 - 3 / (4(n_1 + n_2) - 9)) d × ( 1 − 3/ ( 4 ( n 1 + n 2 ) − 9 ))
d corrected for small samples
difference of rates
p ^ 1 − p ^ 2 \hat{p}_1 - \hat{p}_2 p ^ 1 − p ^ 2
percentage points
relative lift / risk
p ^ 1 / p ^ 2 \hat{p}_1 / \hat{p}_2 p ^ 1 / p ^ 2
stats.contingency.relative_risk
odds ratio
p 1 / ( 1 − p 1 ) p 2 / ( 1 − p 2 ) \frac{p_1/(1-p_1)}{p_2/(1-p_2)} p 2 / ( 1 − p 2 ) p 1 / ( 1 − p 1 )
stats.contingency.odds_ratio; 1 = no effect
rank-biserial r
2 U / ( n 1 n 2 ) − 1 2U / (n_1 n_2) - 1 2 U / ( n 1 n 2 ) − 1
−1 to 1; 0 = no tendency
Pearson r, Spearman ρ
pearsonr, spearmanr
0.1 small, 0.3 medium, 0.5 large
Cramér’s V
stats.contingency.association(table)
0.1 weak, 0.3 moderate (2 columns)
η² (ANOVA)
between-group SS / total SS
share of variance explained
def cohens_d (a: np.ndarray, b: np.ndarray) -> float :
"""Standardized mean difference with the pooled standard deviation."""
pooled = ((n1 - 1 ) * a.var( ddof = 1 ) + (n2 - 1 ) * b.var( ddof = 1 )) / (n1 + n2 - 2 )
return (a.mean() - b.mean()) / np.sqrt(pooled)
print ( round (cohens_d(t_time, c_time), 3 )) # tiny p, effect below "small" (0.2)
u = stats.mannwhitneyu(t_rev, c_rev).statistic
print ( round ( 2 * u / ( len (t_rev) * len (c_rev)) - 1 , 3 )) # rank-biserial r
rr = stats.contingency.relative_risk( 583 , 4998 , 506 , 5002 ) # k_t, n_t, k_c, n_c
print ( round (rr.relative_risk, 3 ), np.round(rr.confidence_interval(), 3 ))
odds = stats.contingency.odds_ratio([[ 583 , 4415 ], [ 506 , 4496 ]], kind = "sample" )
print ( round (odds.statistic, 3 ), np.round(odds.confidence_interval(), 3 ))
v = stats.contingency.association(pd.crosstab(ab[ "device" ], ab[ "converted" ]))
print ( round (v, 3 )) # Cramer's V: a weak association
Interval for
Code
a mean
stats.t.interval(0.95, len(x) - 1, loc=x.mean(), scale=stats.sem(x))
a difference of means
stats.ttest_ind(a, b, equal_var=False).confidence_interval()
a paired difference
stats.ttest_rel(after, before).confidence_interval()
a proportion
stats.binomtest(k, n).proportion_ci(method="wilson")
a correlation
stats.pearsonr(x, y).confidence_interval()
an odds ratio / relative risk
.confidence_interval() on the contingency results
any statistic
stats.bootstrap(...) (next section)
m, se = t_time.mean(), stats.sem(t_time)
print (np.round(stats.t.interval( 0.95 , len (t_time) - 1 , loc = m, scale = se), 2 ))
ci = stats.binomtest( 583 , 4998 ).proportion_ci( confidence_level = 0.95 , method = "wilson" )
print ( round (ci.low, 4 ), round (ci.high, 4 )) # treatment conversion rate
stats.bootstrap resamples the data with replacement, recomputes the statistic and builds a CI from the spread of the results. Use it for medians, ratios, trimmed means and other statistics with no simple formula.
Argument
Meaning
data
a tuple of samples: (x,) for one, (a, b) for two (resampled separately)
statistic
a function of the samples; with an axis argument it runs vectorized (fast)
n_resamples=9999
the number of resamples
method="BCa"
also "percentile", "basic"; BCa corrects for bias and skew
paired=True
resample pairs together (data=(x, y) of equal length)
confidence_level=0.95
the CI level
rng=np.random.default_rng(42)
repeatable results
Result
Gives
res.confidence_interval
.low, .high
res.standard_error
the bootstrap standard error
res.bootstrap_distribution
every resampled statistic (for a histogram)
rng = np.random.default_rng( 42 )
boot = stats.bootstrap((rev,), np.median, rng = rng) # one sample: note the comma
print (np.round(boot.confidence_interval, 2 ), round (boot.standard_error, 3 ))
def diff_medians (a: np.ndarray, b: np.ndarray, axis: int ) -> np.ndarray:
return np.median(a, axis = axis) - np.median(b, axis = axis)
two = stats.bootstrap((t_rev.to_numpy(), c_rev.to_numpy()), diff_medians, rng = rng)
print (np.round(two.confidence_interval, 2 )) # includes 0: no clear change
print (two.bootstrap_distribution.shape)
stats.permutation_test builds the null distribution by shuffling. Under H0 the labels do not matter, so the observed statistic should look like the shuffled ones. The p-value is the share of shuffled statistics at least as extreme as the observed one.
permutation_type
Shuffles
Use for
data
"independent" (default)
values between the groups
two or more independent groups
(a, b)
"samples"
within each pair (signs of the difference)
paired data
(after, before)
"pairings"
which x goes with which y
correlation
(x, y)
def diff_means (a: np.ndarray, b: np.ndarray, axis: int ) -> np.ndarray:
return a.mean( axis = axis) - b.mean( axis = axis)
res = stats.permutation_test(
(t_time, c_time), diff_means, n_resamples = 2_000 , vectorized = True , rng = rng
print ( round (res.statistic, 2 ), round (res.pvalue, 4 )) # no shuffle came close
paired = stats.permutation_test(
(after, before), diff_means, permutation_type = "samples" , rng = rng
print ( round (paired.statistic, 3 ), round (paired.pvalue, 4 )) # 2**8 = 256: exact
def pearson_r (x: np.ndarray, y: np.ndarray) -> float :
return stats.pearsonr(x, y).statistic
corr = stats.permutation_test(
(before, after), pearson_r, permutation_type = "pairings" , rng = rng
print ( round (corr.statistic, 3 ), round (corr.pvalue, 4 ))
The first p-value is the smallest possible one with 2,000 shuffles: 2 / 2001 2 / 2001 2/2001 for a two-sided test. Raise n_resamples for more resolution. With few possible arrangements, as for 8 pairs, the test enumerates them all and the p-value is exact.
The tests also accept a resampling method: stats.ttest_ind(a, b, method=stats.PermutationMethod(rng=rng)) and stats.pearsonr(x, y, method=stats.PermutationMethod()) keep their usual statistic but compute the p-value by permutation.
Trap
Symptom
Fix
ttest_ind(a, b) with unequal variances
p-value too small or too large
equal_var=False (Welch) by default
sf(k) for “at least k” on a discrete distribution
off by one value
sf(k - 1)
stats.expon(lam)
the mean is wrong: the first argument is loc
stats.expon(scale=1 / lam)
stats.uniform(a, b)
the range is a to a + b
stats.uniform(loc=a, scale=b - a)
stats.lognorm(mu, sigma)
nonsense values
stats.lognorm(s=sigma, scale=np.exp(mu))
stats.geom.pmf(0, p) is 0
counts start at 1
use k - 1 failures or stats.nbinom(1, p)
dist(...).fit(x)
AttributeError: a frozen distribution has no fit
stats.norm.fit(x) on the class
stats.fit(stats.norm, x)
loc=0, scale=1, whatever the data
pass bounds for loc and scale, or use stats.norm.fit
lognorm.fit(x) without floc=0
a 3-parameter fit with a strange loc
floc=0
kstest with parameters fitted on the same data
p-values far too large
stats.goodness_of_fit
stats.anderson(x)
FutureWarning in SciPy 1.17+
pass method="interpolate" or a MonteCarloMethod
chisquare(obs, f_exp=shares)
ValueError: the sums of observed and expected frequencies differ
expected counts: f_exp=np.array(shares) * obs.sum()
chi2_contingency on a 2×2 table
p differs from a z-test of two rates
Yates’ correction; correction=False matches the z-test
odds_ratio(table)
differs a little from the hand formula
the default is the conditional MLE; kind="sample" for the plain ratio
stats.bootstrap(x, ...)
AxisError: axis is out of bounds for array of dimension 0
pass a tuple: (x,)
a non-vectorized statistic
bootstrap or permutation_test is slow
accept axis and use .mean(axis=axis)
no rng
different results on every run
rng=np.random.default_rng(42)
permutation p-value of 0.0005 or 0.001
it is the floor, not the truth
the floor is 1 / (n_resamples + 1) (two-sided: twice that); raise n_resamples
mannwhitneyu read as a test of medians
wrong conclusion when shapes differ
it tests whether one group tends to give larger values
alternative="greater"
the direction is reversed
it refers to the first argument minus the second
shapiro on thousands of rows
rejects harmless departures
read a Q-Q plot (stats.probplot)
pearsonr on trending or skewed data
strong but spurious r
spearmanr, logs, or differences
NaN in the input
the result is nan
nan_policy="omit" or dropna() first
many tests at α = 0.05
false discoveries
stats.false_discovery_control(p)