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.
Quick reference
Section titled “Quick reference”| 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 pltimport numpy as npimport pandas as pdfrom scipy import cluster, optimize, signal, sparse, spatial, stats
rng = np.random.default_rng(42)Path("outputs").mkdir(exist_ok=True)Two groups
Section titled “Two groups”Welch’s t-test
Section titled “Welch’s t-test”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-05difference in means, 95% CI: 1.32 to 3.18Mann-Whitney U
Section titled “Mann-Whitney U”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-05Paired samples
Section titled “Paired samples”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-06Wilcoxon: W = 0, p = 4.88e-04Shapiro-Wilk normality test
Section titled “Shapiro-Wilk normality test”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.416Levene’s test for equal variances
Section titled “Levene’s test for equal variances”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.169Resampling
Section titled “Resampling”permutation_test
Section titled “permutation_test”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.251permutation p = 0.0002The 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
Section titled “bootstrap”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_intervalprint(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.47Three or more groups
Section titled “Three or more groups”One-way ANOVA and Kruskal-Wallis
Section titled “One-way ANOVA and Kruskal-Wallis”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-07Kruskal-Wallis: H = 22.76, p = 1.14e-05Tukey’s HSD
Section titled “Tukey’s HSD”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.112Correlation
Section titled “Correlation”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-09Spearman rho = 0.710, p = 2.9e-07Contingency tables
Section titled “Contingency tables”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-03expected counts:[[22.5 17.5] [22.5 17.5]]Fisher: odds ratio = 5.00, p = 1.43e-03Distributions
Section titled “Distributions”cdf, sf, ppf, pmf
Section titled “cdf, sf, ppf, pmf”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.9750P(Z > 1.96) = 0.025097.5% quantile = 1.9600Poisson 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.2n_param = 1 / alphap_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.0six 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.3axes[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)
Multiple testing
Section titled “Multiple testing”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. ]Curve fitting
Section titled “Curve fitting”curve_fit
Section titled “curve_fit”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.433bottom = 9.730 +/- 1.998 EC50 = 1.599 +/- 0.173 slope = 1.306 +/- 0.171dose_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)
Distances and clustering
Section titled “Distances and clustering”pdist and squareform
Section titled “pdist and squareform”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 CCNB1TP53 0.00 0.09 0.20 1.85 1.79 1.88CDKN1A 0.09 0.00 0.07 1.95 1.92 1.97MDM2 0.20 0.07 0.00 1.95 1.95 1.97MKI67 1.85 1.95 1.95 0.00 0.12 0.04TOP2A 1.79 1.92 1.95 0.12 0.00 0.03CCNB1 1.88 1.97 1.97 0.04 0.03 0.00pdist returns the condensed upper triangle, n(n - 1) / 2 values, which is what linkage
expects. Other metrics include "euclidean", "cosine", "cityblock", and "jaccard".
zscore
Section titled “zscore”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 S8TP53 0.40 0.70 1.41 0.65 -1.28 -0.57 0.08 -1.41CDKN1A 0.73 1.13 1.15 0.65 -0.98 -0.88 -0.69 -1.12MDM2 1.01 0.81 0.75 1.07 -0.87 -1.36 -0.68 -0.73MKI67 -0.87 -1.00 -0.72 -1.01 0.54 1.01 0.62 1.41TOP2A -0.42 -0.95 -0.90 -1.28 1.16 1.09 0.87 0.43CCNB1 -0.61 -0.94 -1.01 -1.12 0.95 1.09 0.69 0.94linkage and fcluster
Section titled “linkage and fcluster”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 2CDKN1A 2MDM2 2MKI67 1TOP2A 1CCNB1 1Name: module, dtype: int32dendrogram
Section titled “dendrogram”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)
Sparse matrices
Section titled “Sparse matrices”csr_array
Section titled “csr_array”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 190012density 0.095dense 16.0 MB, CSR 2.3 MBSums and slicing
Section titled “Sums and slicing”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 valuesCSR slices rows fast, so it suits per-cell work. CSC slices columns fast, so convert with
tocsc() before many per-gene operations.
Peak detection
Section titled “Peak detection”find_peaks
Section titled “find_peaks”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.003peak at 7.51 min, height 0.614peak at 8.10 min, height 0.360peak at 13.01 min, height 0.809fig, 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)
signal.peak_widths(trace, peaks) returns the width of each peak at half its prominence,
which feeds a peak area estimate.
See also
Section titled “See also”- Two Groups: t-test & Wilcoxon
- Multiple Groups: ANOVA & Kruskal-Wallis
- Categorical Data: Chi-square & Fisher
- Correlation
- Multiple Testing Correction
- statsmodels cheatsheet
Scientific references
Section titled “Scientific references”Virtanen and colleagues, 2020 describe SciPy 1.0 and its fundamental algorithms for scientific computing in Python.
Further reading
Section titled “Further reading”-
SciPy independent-sample tests
The reference distinguishes equal-variance and Welch tests and defines the returned statistics.
-
The reference explains initial values, parameter bounds, covariance, and poorly identified parameters.