SciPy Cheat Sheet
SciPy scientific computing reference covering statistics, optimization, linear algebra, and interpolation for numerical Python workflows.
scipy.stats
Distributions and hypothesis tests.
from scipy import statst_stat, p_value = stats.ttest_ind(group_a, group_b) # two-sample t-testr, p = stats.pearsonr(x, y) # Pearson correlationdist = stats.norm(loc=0, scale=1)print(dist.pdf(0), dist.cdf(1.96))z_scores = stats.zscore(data)
scipy.optimize
Minimization and root finding.
from scipy import optimizedef f(x): return (x[0] - 3) ** 2 + (x[1] + 1) ** 2result = optimize.minimize(f, x0=[0, 0], method="BFGS")print(result.x, result.fun)root = optimize.brentq(lambda x: x ** 2 - 4, 0, 5) # find root in [0, 5]
Linear Algebra & Interpolation
Solve systems and interpolate data.
from scipy import linalg, interpolateA = [[2, 1], [1, 3]]b = [3, 5]x = linalg.solve(A, b) # solve Ax = beigvals, eigvecs = linalg.eig(A)f = interpolate.interp1d(x_known, y_known, kind="cubic")y_new = f(x_query)
Key Submodules
Major areas of SciPy's functionality.
- scipy.stats- probability distributions and hypothesis tests
- scipy.optimize- minimization, curve fitting, root finding
- scipy.linalg- linear algebra beyond NumPy (LU, eig, solve)
- scipy.sparse- sparse matrix formats and operations
- scipy.signal- filtering, convolution, spectral analysis
- scipy.spatial- distance metrics, KD-trees, Voronoi diagrams
- scipy.integrate- numerical integration and ODE solvers
- scipy.interpolate- 1D/2D interpolation of data points
Sparse Matrices & Solvers
Work with large sparse systems efficiently instead of dense arrays.
from scipy import sparsefrom scipy.sparse.linalg import spsolve, eigshA = sparse.csr_matrix(([4, 1, 1, 3], ([0, 0, 1, 1], [0, 1, 0, 1])), shape=(2, 2))b = sparse.csr_matrix([[1], [2]])x = spsolve(A, b.toarray().ravel())# smallest-magnitude eigenvalues of a large symmetric sparse matrixvals, vecs = eigsh(A.astype(float), k=1, which="SM")
Constrained & Global Optimization
Add bounds/constraints, or escape local minima with global solvers.
from scipy.optimize import minimize, differential_evolution, LinearConstraintcons = LinearConstraint([[1, 1]], lb=-1, ub=1) # x0 + x1 in [-1, 1]result = minimize( f, x0=[0, 0], method="SLSQP", bounds=[(-5, 5), (-5, 5)], constraints=[cons],)# global optimizer, useful when the objective is non-convexresult_global = differential_evolution(f, bounds=[(-5, 5), (-5, 5)], seed=0)
Signal Filtering & Spectral Analysis
Design filters and inspect frequency content with scipy.signal.
from scipy import signal# 4th-order low-pass Butterworth filter, zero-phaseb, a = signal.butter(4, Wn=0.2, btype="low")filtered = signal.filtfilt(b, a, raw_signal)freqs, psd = signal.welch(raw_signal, fs=1000, nperseg=256) # power spectral densitypeaks, props = signal.find_peaks(raw_signal, height=0.5, distance=20)
ODE Integration
Solve systems of ordinary differential equations with adaptive step sizing.
from scipy.integrate import solve_ivpdef lotka_volterra(t, state, a, b, c, d): x, y = state return [a * x - b * x * y, -c * y + d * x * y]sol = solve_ivp( lotka_volterra, t_span=(0, 50), y0=[10, 5], args=(1.1, 0.4, 0.4, 0.1), method="RK45", dense_output=True, t_eval=np.linspace(0, 50, 500),)print(sol.y.shape) # (2, 500)
Choosing a Hypothesis Test
Which scipy.stats test fits which data assumption.
- ttest_ind(equal_var=False)- Welch's t-test for two independent samples with unequal variance
- mannwhitneyu- non-parametric alternative to the t-test when normality can't be assumed
- shapiro / normaltest- test whether a sample is drawn from a normal distribution
- kruskal- non-parametric alternative to one-way ANOVA across 3+ groups
- chi2_contingency- test independence between two categorical variables in a contingency table
- wilcoxon- paired non-parametric test for matched before/after samples
- multipletests (statsmodels) or bonferroni manually- correct p-values when running many tests to control family-wise error rate
scipy.optimize.curve_fit is often simpler than minimize for fitting a parametric function to data — it wraps least-squares fitting and returns both the parameters and their covariance matrix for uncertainty estimates.