Skip to content

SciPy

SciPy holds the classical statistics under most bench analyses: two-group tests, contingency tables, probability distributions, and Benjamini-Hochberg correction. It also fits dose-response curves, clusters co-expressed genes, and stores the sparse count matrices that single-cell tools pass around. Every block below ran with SciPy 1.18 and NumPy 2.5.

Task Call
Welch’s t-test stats.ttest_ind(a, b, equal_var=False)
Paired t-test stats.ttest_rel(after, before)
Mann-Whitney U stats.mannwhitneyu(a, b, alternative="two-sided")
Wilcoxon signed-rank stats.wilcoxon(after, before)
Normality test stats.shapiro(x)
Equal variances stats.levene(a, b)
Permutation test stats.permutation_test((a, b), stat, rng=rng)
Bootstrap CI stats.bootstrap((x,), np.median, rng=rng)
One-way ANOVA stats.f_oneway(g1, g2, g3)
Kruskal-Wallis stats.kruskal(g1, g2, g3)
Tukey’s HSD stats.tukey_hsd(g1, g2, g3)
Correlation stats.pearsonr(x, y), stats.spearmanr(x, y)
Chi-square stats.chi2_contingency(table)
Fisher’s exact stats.fisher_exact(table)
Tail probability stats.norm.sf(z)
BH adjustment stats.false_discovery_control(p, method="bh")
Curve fit optimize.curve_fit(f, x, y, p0=..., bounds=...)
Pairwise distances spatial.distance.pdist(x, metric="correlation")
Row z-scores stats.zscore(x, axis=1, ddof=1)
Hierarchical clustering cluster.hierarchy.linkage(d, method="average")
Cut a tree cluster.hierarchy.fcluster(link, t=2, criterion="maxclust")
Sparse counts sparse.csr_array(dense)
Peak finding signal.find_peaks(trace, height=..., prominence=...)
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import cluster, optimize, signal, sparse, spatial, stats
rng = np.random.default_rng(42)
Path("outputs").mkdir(exist_ok=True)

The example measures one gene in 30 control and 30 treated samples. equal_var=False gives Welch’s test, which does not assume equal variances, while the default True gives Student’s test. The result object carries the degrees of freedom and a confidence interval for the difference.

control = rng.normal(loc=10, scale=2, size=30)
treated = rng.normal(loc=12, scale=2.5, size=30)
res = stats.ttest_ind(treated, control, equal_var=False)
ci = res.confidence_interval(confidence_level=0.95)
print(f"t = {res.statistic:.3f}, df = {res.df:.1f}, p = {res.pvalue:.2e}")
print(f"difference in means, 95% CI: {ci.low:.2f} to {ci.high:.2f}")
t = 4.850, df = 54.5, p = 1.07e-05
difference in means, 95% CI: 1.32 to 3.18

mannwhitneyu runs the rank-based test on the same two groups. Pass alternative explicitly, since a one-sided test by mistake halves the p-value.

res_mw = stats.mannwhitneyu(treated, control, alternative="two-sided")
print(f"U = {res_mw.statistic:.0f}, p = {res_mw.pvalue:.2e}")
U = 724, p = 5.27e-05

Here the same 12 patients are measured before and after treatment. ttest_rel tests the mean of the paired differences, and wilcoxon is the signed-rank version.

before = rng.normal(loc=8, scale=1.5, size=12)
after = before + rng.normal(loc=0.8, scale=0.6, size=12)
res_paired = stats.ttest_rel(after, before)
res_signed = stats.wilcoxon(after, before)
print(f"paired t: t = {res_paired.statistic:.3f}, "
f"p = {res_paired.pvalue:.2e}")
print(f"Wilcoxon: W = {res_signed.statistic:.0f}, "
f"p = {res_signed.pvalue:.2e}")
paired t: t = 8.315, p = 4.52e-06
Wilcoxon: W = 0, p = 4.88e-04

A small p-value says the sample is unlikely to come from a normal distribution. With 30 values the test has little power, so read it next to a QQ plot rather than alone.

res_sw = stats.shapiro(control)
print(f"W = {res_sw.statistic:.3f}, p = {res_sw.pvalue:.3f}")
W = 0.965, p = 0.416

levene asks whether the groups share one variance. The default center="median" is the Brown-Forsythe version, which holds up when the data are skewed.

res_lev = stats.levene(control, treated)
print(f"W = {res_lev.statistic:.3f}, p = {res_lev.pvalue:.3f}")
W = 1.944, p = 0.169

A permutation test shuffles the group labels and recomputes the statistic, so it needs no distribution assumption. With vectorized=True the statistic must take an axis argument. Pass a seeded generator to rng; older code passes random_state.

def mean_difference(x, y, axis):
"""Difference between two group means.
Args:
x: First sample.
y: Second sample.
axis: Axis along which to take the means.
Returns:
The mean of x minus the mean of y.
"""
return np.mean(x, axis=axis) - np.mean(y, axis=axis)
res_perm = stats.permutation_test(
(treated, control), mean_difference, permutation_type="independent",
vectorized=True, n_resamples=9999, rng=np.random.default_rng(42),
)
print(f"observed difference = {res_perm.statistic:.3f}")
print(f"permutation p = {res_perm.pvalue:.4f}")
observed difference = 2.251
permutation p = 0.0002

The two-sided p-value doubles the smaller one-sided p-value, and each one-sided p-value is at least 1 / (n_resamples + 1). With 9,999 resamples the floor is 0.0002, which is what this run returns, so raise n_resamples when you need to resolve a smaller p.

bootstrap resamples the data with replacement to get a confidence interval for any statistic. The default method="BCa" corrects for bias and skew.

res_boot = stats.bootstrap(
(treated,), np.median, confidence_level=0.95, n_resamples=9999,
method="BCa", rng=np.random.default_rng(42),
)
boot_ci = res_boot.confidence_interval
print(f"median = {np.median(treated):.2f}, "
f"95% CI {boot_ci.low:.2f} to {boot_ci.high:.2f}")
median = 12.42, 95% CI 11.09 to 13.47

The example measures one gene at three doses, with 15 samples at each dose.

dose_low = rng.normal(loc=5.0, scale=1.0, size=15)
dose_mid = rng.normal(loc=5.6, scale=1.0, size=15)
dose_high = rng.normal(loc=6.5, scale=1.0, size=15)
res_anova = stats.f_oneway(dose_low, dose_mid, dose_high)
res_kw = stats.kruskal(dose_low, dose_mid, dose_high)
print(f"ANOVA: F = {res_anova.statistic:.2f}, "
f"p = {res_anova.pvalue:.2e}")
print(f"Kruskal-Wallis: H = {res_kw.statistic:.2f}, p = {res_kw.pvalue:.2e}")
ANOVA: F = 22.79, p = 1.98e-07
Kruskal-Wallis: H = 22.76, p = 1.14e-05

tukey_hsd compares every pair of groups after the ANOVA and adjusts for the number of comparisons. Groups are numbered in the order they were passed.

print(stats.tukey_hsd(dose_low, dose_mid, dose_high))
Pairwise Group Comparisons (95.0% Confidence Interval)
Comparison Statistic p-value Lower CI Upper CI
(0 - 1) -0.663 0.090 -1.408 0.082
(0 - 2) -2.030 0.000 -2.775 -1.285
(1 - 0) 0.663 0.090 -0.082 1.408
(1 - 2) -1.367 0.000 -2.112 -0.622
(2 - 0) 2.030 0.000 1.285 2.775
(2 - 1) 1.367 0.000 0.622 2.112

Two genes are measured in 40 samples, and the first partly drives the second. pearsonr returns a confidence interval for r; spearmanr works on ranks and tolerates outliers.

gene_a = rng.normal(size=40)
gene_b = 0.7 * gene_a + rng.normal(scale=0.6, size=40)
res_pearson = stats.pearsonr(gene_a, gene_b)
res_spearman = stats.spearmanr(gene_a, gene_b)
ci = res_pearson.confidence_interval(confidence_level=0.95)
print(f"Pearson r = {res_pearson.statistic:.3f} "
f"(95% CI {ci.low:.3f} to {ci.high:.3f}), p = {res_pearson.pvalue:.1e}")
print(f"Spearman rho = {res_spearman.statistic:.3f}, "
f"p = {res_spearman.pvalue:.1e}")
Pearson r = 0.777 (95% CI 0.614 to 0.876), p = 3.8e-09
Spearman rho = 0.710, p = 2.9e-07

The table counts responders and non-responders by genotype in 80 patients. On a 2 x 2 table chi2_contingency applies the Yates continuity correction unless you pass correction=False. Older code unpacks the result as a tuple, which still works.

observed = np.array([[30, 10], [15, 25]])
res_chi2 = stats.chi2_contingency(observed)
res_fisher = stats.fisher_exact(observed)
print(f"chi2 = {res_chi2.statistic:.3f}, dof = {res_chi2.dof}, "
f"p = {res_chi2.pvalue:.2e}")
print("expected counts:")
print(res_chi2.expected_freq)
print(f"Fisher: odds ratio = {res_fisher.statistic:.2f}, "
f"p = {res_fisher.pvalue:.2e}")
chi2 = 9.956, dof = 1, p = 1.60e-03
expected counts:
[[22.5 17.5]
[22.5 17.5]]
Fisher: odds ratio = 5.00, p = 1.43e-03

Every distribution has the same methods: pdf or pmf for the density, cdf for the lower tail, sf for the upper tail, and ppf for quantiles.

print(f"P(Z < 1.96) = {stats.norm.cdf(1.96):.4f}")
print(f"P(Z > 1.96) = {stats.norm.sf(1.96):.4f}")
print(f"97.5% quantile = {stats.norm.ppf(0.975):.4f}")
print(f"Poisson pmf, mu=2 = {stats.poisson.pmf(np.arange(5), mu=2).round(3)}")
P(Z < 1.96) = 0.9750
P(Z > 1.96) = 0.0250
97.5% quantile = 1.9600
Poisson pmf, mu=2 = [0.135 0.271 0.271 0.18 0.09 ]

Negative binomial from a mean and a dispersion

Section titled “Negative binomial from a mean and a dispersion”

DESeq2 and edgeR describe a gene’s counts by a mean mu and a dispersion alpha, with variance mu + alpha * mu**2. SciPy’s nbinom takes n and p instead. Set n = 1 / alpha and p = n / (n + mu) to move between the two.

mu, alpha = 100.0, 0.2
n_param = 1 / alpha
p_param = n_param / (n_param + mu)
nb = stats.nbinom(n_param, p_param)
print(f"mean = {nb.mean():.1f}, variance = {nb.var():.1f}")
print(f"six draws: {nb.rvs(size=6, random_state=rng)}")
mean = 100.0, variance = 2100.0
six draws: [ 86 74 187 89 106 90]

The left panel shades the two 2.5% tails of the standard normal. The right panel puts a Poisson and a negative binomial with the same mean side by side.

fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))
grid = np.linspace(-4, 4, 400)
density = stats.norm.pdf(grid)
axes[0].plot(grid, density, color="black")
axes[0].fill_between(grid, density, where=np.abs(grid) > 1.96,
color="tab:red", alpha=0.5)
axes[0].set(title="Normal(0, 1), 5% in the tails", xlabel="z",
ylabel="density")
counts = np.arange(0, 41)
n_disp = 1 / 0.3
axes[1].plot(counts, stats.poisson.pmf(counts, mu=10), "o-", ms=3,
label="Poisson, mean 10")
axes[1].plot(counts, stats.nbinom.pmf(counts, n_disp, n_disp / (n_disp + 10)),
"s-", ms=3, label="NB, mean 10, alpha 0.3")
axes[1].set(title="Same mean, wider spread", xlabel="count",
ylabel="probability")
axes[1].legend(frameon=False)
fig.tight_layout()
fig.savefig("outputs/scipy-distributions.png", dpi=150)
plt.close(fig)

Two panels. Left, the standard normal density with the regions below -1.96 and above 1.96 shaded red. Right, the Poisson probability mass function with mean 10 peaks near 0.125 at counts 9 and 10, while the negative binomial with the same mean and dispersion 0.3 peaks near 0.073 at counts 6 and 7 and still has visible probability past a count of 30.

false_discovery_control returns Benjamini-Hochberg adjusted p-values with method="bh" and Benjamini-Yekutieli with method="by". SciPy added it in 1.11. Older code sorts the p-values by hand, or calls multipletests from statsmodels, which also offers Bonferroni and Holm.

raw_p = np.array([0.001, 0.008, 0.012, 0.03, 0.04, 0.15, 0.25, 0.5, 0.8])
print(f"BH: {stats.false_discovery_control(raw_p, method='bh').round(3)}")
print(f"BY: {stats.false_discovery_control(raw_p, method='by').round(3)}")
BH: [0.009 0.036 0.036 0.068 0.072 0.225 0.321 0.562 0.8 ]
BY: [0.025 0.102 0.102 0.191 0.204 0.637 0.909 1. 1. ]

The example fits a four-parameter Hill curve to a nine-point dose series. bounds=(0, np.inf) keeps every parameter positive, so the EC50 cannot wander below zero. The square roots of the diagonal of pcov are the standard errors.

def hill(dose, top, bottom, ec50, slope):
"""Four-parameter logistic dose-response curve.
Args:
dose: Drug concentrations, all above zero.
top: Response at a saturating dose.
bottom: Response with no drug.
ec50: Dose that gives half the maximal effect.
slope: Hill coefficient.
Returns:
The predicted response at each dose.
"""
return bottom + (top - bottom) / (1 + (ec50 / dose) ** slope)
doses = np.array([0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30, 100])
response = hill(doses, 100, 10, 1.5, 1.2) + rng.normal(0, 3, doses.size)
popt, pcov = optimize.curve_fit(
hill, doses, response, p0=[100, 10, 1, 1], bounds=(0, np.inf)
)
std_err = np.sqrt(np.diag(pcov))
names = ["top", "bottom", "EC50", "slope"]
for name, value, err in zip(names, popt, std_err, strict=True):
print(f"{name:>6} = {value:7.3f} +/- {err:.3f}")
top = 97.840 +/- 2.433
bottom = 9.730 +/- 1.998
EC50 = 1.599 +/- 0.173
slope = 1.306 +/- 0.171
dose_grid = np.logspace(-2, 2, 200)
fig, ax = plt.subplots(figsize=(5, 3.5))
ax.scatter(doses, response, color="black", zorder=3, label="measured")
ax.plot(dose_grid, hill(dose_grid, *popt), color="tab:blue", label="fit")
ax.axvline(popt[2], color="grey", linestyle="--", linewidth=1)
ax.set_xscale("log")
ax.set(xlabel="dose (uM)", ylabel="response (%)",
title=f"EC50 = {popt[2]:.2f} uM")
ax.legend(frameon=False)
fig.tight_layout()
fig.savefig("outputs/scipy-dose-response.png", dpi=150)
plt.close(fig)

Nine measured points rise from about 10 percent response at 0.01 uM to about 99 percent at 100 uM on a log dose axis. The fitted Hill curve passes through them, and a dashed vertical line marks the fitted EC50 of 1.60 uM.

The matrix holds six genes across eight samples. The three p53 targets rise in the first four samples and the three proliferation genes rise in the last four. Correlation distance is one minus the Pearson correlation, so genes that move together sit near 0 and opposite genes near 2.

genes = ["TP53", "CDKN1A", "MDM2", "MKI67", "TOP2A", "CCNB1"]
damage = np.array([2.0, 2.2, 1.8, 2.1, 0.2, 0.0, 0.3, 0.1])
pattern = np.vstack([damage] * 3 + [2.2 - damage] * 3)
expr = pattern + rng.normal(scale=0.3, size=pattern.shape)
dist_vec = spatial.distance.pdist(expr, metric="correlation")
dist_mat = pd.DataFrame(
spatial.distance.squareform(dist_vec), index=genes, columns=genes
)
print(dist_mat.round(2))
TP53 CDKN1A MDM2 MKI67 TOP2A CCNB1
TP53 0.00 0.09 0.20 1.85 1.79 1.88
CDKN1A 0.09 0.00 0.07 1.95 1.92 1.97
MDM2 0.20 0.07 0.00 1.95 1.95 1.97
MKI67 1.85 1.95 1.95 0.00 0.12 0.04
TOP2A 1.79 1.92 1.95 0.12 0.00 0.03
CCNB1 1.88 1.97 1.97 0.04 0.03 0.00

pdist returns the condensed upper triangle, n(n - 1) / 2 values, which is what linkage expects. Other metrics include "euclidean", "cosine", "cityblock", and "jaccard".

zscore with axis=1 scales each gene across the samples to mean 0 and standard deviation 1, which is the usual step before a heatmap. ddof=1 uses the sample standard deviation.

z = stats.zscore(expr, axis=1, ddof=1)
samples = [f"S{i}" for i in range(1, 9)]
print(pd.DataFrame(z, index=genes, columns=samples).round(2))
S1 S2 S3 S4 S5 S6 S7 S8
TP53 0.40 0.70 1.41 0.65 -1.28 -0.57 0.08 -1.41
CDKN1A 0.73 1.13 1.15 0.65 -0.98 -0.88 -0.69 -1.12
MDM2 1.01 0.81 0.75 1.07 -0.87 -1.36 -0.68 -0.73
MKI67 -0.87 -1.00 -0.72 -1.01 0.54 1.01 0.62 1.41
TOP2A -0.42 -0.95 -0.90 -1.28 1.16 1.09 0.87 0.43
CCNB1 -0.61 -0.94 -1.01 -1.12 0.95 1.09 0.69 0.94

linkage joins the genes by average linkage on the correlation distances, and fcluster cuts the tree into two clusters. Ward linkage assumes Euclidean distances, so give it the expression matrix or a Euclidean pdist, never a correlation distance.

link = cluster.hierarchy.linkage(dist_vec, method="average")
modules = cluster.hierarchy.fcluster(link, t=2, criterion="maxclust")
print(pd.Series(modules, index=genes, name="module"))
TP53 2
CDKN1A 2
MDM2 2
MKI67 1
TOP2A 1
CCNB1 1
Name: module, dtype: int32
fig, ax = plt.subplots(figsize=(6, 3.5))
cluster.hierarchy.dendrogram(link, labels=genes, ax=ax)
ax.set_ylabel("correlation distance")
fig.tight_layout()
fig.savefig("outputs/scipy-dendrogram.png", dpi=150)
plt.close(fig)

Dendrogram of six genes. MKI67, TOP2A, and CCNB1 join below a correlation distance of 0.1, and TP53, CDKN1A, and MDM2 join below 0.15. The two groups merge only at a distance of about 1.9.

The simulated count matrix has 2,000 cells by 1,000 genes and is mostly zeros. CSR stores only the non-zero values, their column indices, and one pointer per row.

dense = rng.poisson(0.1, size=(2000, 1000))
counts_csr = sparse.csr_array(dense)
csr_bytes = (counts_csr.data.nbytes + counts_csr.indices.nbytes
+ counts_csr.indptr.nbytes)
print(f"shape {counts_csr.shape}, stored values {counts_csr.nnz}")
print(f"density {counts_csr.nnz / dense.size:.3f}")
print(f"dense {dense.nbytes / 1e6:.1f} MB, CSR {csr_bytes / 1e6:.1f} MB")
shape (2000, 1000), stored values 190012
density 0.095
dense 16.0 MB, CSR 2.3 MB

SciPy now recommends the sparse array classes, csr_array and csc_array, over the older csr_matrix. On an array, .sum(axis=1) returns a 1-D result and * multiplies element by element, as in NumPy. On a csr_matrix, .sum returns a 2-D matrix and * is the matrix product, which is the trap when code moves between the two. Use @ for a matrix product on either.

cell_totals = counts_csr.sum(axis=1)
print(f"cell totals: shape {cell_totals.shape}, first five {cell_totals[:5]}")
counts_csc = counts_csr.tocsc()
first_genes = counts_csc[:, :50]
print(f"first 50 genes: shape {first_genes.shape}, {first_genes.nnz} values")
cell totals: shape (2000,), first five [107 108 101 96 87]
first 50 genes: shape (2000, 50), 9574 values

CSR slices rows fast, so it suits per-cell work. CSC slices columns fast, so convert with tocsc() before many per-gene operations.

The example simulates a chromatogram with four peaks on a 20 minute run, two of them close together. height drops noise spikes, prominence asks how far a peak stands above its surroundings, and distance sets the minimum gap in samples between two peaks.

time_min = np.linspace(0, 20, 2001)
peak_specs = [(4.2, 1.0, 0.10), (7.5, 0.6, 0.15), (8.1, 0.35, 0.12),
(13.0, 0.8, 0.20)]
trace = sum(
height * np.exp(-0.5 * ((time_min - centre) / width) ** 2)
for centre, height, width in peak_specs
)
trace = trace + rng.normal(scale=0.01, size=time_min.size)
peaks, props = signal.find_peaks(trace, height=0.1, prominence=0.05,
distance=20)
for idx, height in zip(peaks, props["peak_heights"], strict=True):
print(f"peak at {time_min[idx]:5.2f} min, height {height:.3f}")
peak at 4.20 min, height 1.003
peak at 7.51 min, height 0.614
peak at 8.10 min, height 0.360
peak at 13.01 min, height 0.809
fig, ax = plt.subplots(figsize=(7, 3.2))
ax.plot(time_min, trace, color="black", linewidth=0.8)
ax.plot(time_min[peaks], trace[peaks], "v", color="tab:red", ms=7)
ax.set(xlabel="retention time (min)", ylabel="signal",
title=f"{peaks.size} peaks found")
fig.tight_layout()
fig.savefig("outputs/scipy-peaks.png", dpi=150)
plt.close(fig)

Simulated chromatogram over 20 minutes with a flat, slightly noisy baseline near 0. Red markers sit on four peaks: 4.20 minutes with height 1.00, 7.51 minutes with 0.61, 8.10 minutes with 0.36, and 13.01 minutes with 0.81. The peaks at 7.51 and 8.10 minutes overlap at their base.

signal.peak_widths(trace, peaks) returns the width of each peak at half its prominence, which feeds a peak area estimate.

Virtanen and colleagues, 2020 describe SciPy 1.0 and its fundamental algorithms for scientific computing in Python.

  • SciPy independent-sample tests

    The reference distinguishes equal-variance and Welch tests and defines the returned statistics.

  • SciPy curve fitting

    The reference explains initial values, parameter bounds, covariance, and poorly identified parameters.