SciPy Intro
SciPy (short for Scientific Python) is an open-source library of numerical algorithms built on top of NumPy. Where NumPy gives you fast arrays and basic maths on them, SciPy gives you the higher-level tools that scientists and engineers reach for every day: finding the minimum of a function, integrating an equation, solving a system of differential equations, filtering a noisy signal, running a statistical test, or measuring distances between points.
import numpy as np
from scipy import optimize
# Where does the parabola (x - 3)^2 + 1 reach its lowest point?
result = optimize.minimize_scalar(lambda x: (x - 3) ** 2 + 1)
print(f"minimum at x = {result.x:.4f}")
print(f"value there = {result.fun:.4f}")minimum at x = 3.0000
value there = 1.0000
Three lines of SciPy replaced what would otherwise be a hand-written search loop with careful stopping rules. That is the core idea of the library: well-tested algorithms, written mostly in C and Fortran, wrapped in a friendly Python interface.
Why use SciPy?
| Reason | What it means for you |
|---|---|
| Built on NumPy | Everything takes and returns NumPy arrays, so it fits straight into your existing code |
| Battle-tested algorithms | Many routines wrap classic libraries such as LAPACK, MINPACK, QUADPACK and FFTPACK |
| Speed | The heavy lifting happens in compiled code, not in Python loops |
| Breadth | Optimization, statistics, signal processing, linear algebra, sparse matrices, graphs, geometry and more in one package |
| Free and open | BSD-licensed, developed in the open, used in research and industry alike |
What's inside SciPy?
SciPy is organised into subpackages, each focused on one area. You import the subpackage you need:
| Subpackage | Purpose | Covered in |
|---|---|---|
scipy.constants |
Physical and mathematical constants, unit conversions | Constants |
scipy.optimize |
Minimization, root finding, curve fitting, linear programming | Optimizers, Curve Fitting |
scipy.sparse |
Matrices that are mostly zeros | Sparse Data |
scipy.sparse.csgraph |
Graph algorithms (shortest paths, components) | Graphs |
scipy.spatial |
Nearest neighbours, distances, convex hulls | Spatial Data |
scipy.io |
Reading and writing MATLAB and other formats | Matlab Arrays |
scipy.interpolate |
Filling in values between known points | Interpolation |
scipy.stats |
Distributions and statistical tests | Statistics section |
scipy.integrate |
Integrals and differential equations | Integration |
scipy.linalg |
Linear algebra beyond numpy.linalg |
Linear Algebra |
scipy.signal / scipy.fft |
Filters and frequency analysis | Signals and Images |
scipy.ndimage |
Image processing on n-dimensional arrays | Image Processing |
scipy.special |
Special mathematical functions | Special Functions |
scipy.cluster |
K-means and hierarchical clustering | Clustering |
A taste of the breadth
The next example touches three subpackages in a few lines: a constant, an integral and a statistics function.
import numpy as np
from scipy import constants, integrate, stats
# 1. A physical constant: the speed of light in m/s
print("speed of light:", constants.c)
# 2. The area under sin(x) from 0 to pi
area, error = integrate.quad(np.sin, 0, np.pi)
print("area under sin:", round(area, 6))
# 3. Probability that a standard normal value is below 1.96
print("P(Z < 1.96):", round(stats.norm.cdf(1.96), 4))speed of light: 299792458.0
area under sin: 2.0
P(Z < 1.96): 0.975
How this course works
Every example on this site runs in your browser using Pyodide, a version of CPython compiled to WebAssembly that ships with NumPy, SciPy and Matplotlib. The first run downloads the libraries (it can take a few seconds); later runs are fast. Edit any example and press Run to experiment.
All examples are deterministic: whenever we need random data we create it with a seeded generator such as np.random.default_rng(42), so you will always see exactly the output printed below the code.
import numpy as np
from scipy import stats
rng = np.random.default_rng(42)
heights = rng.normal(loc=170, scale=8, size=200) # 200 simulated heights in cm
summary = stats.describe(heights)
print("count:", summary.nobs)
print("mean :", round(summary.mean, 2))
print("min/max:", np.round(summary.minmax, 1))count: 200
mean : 169.76
min/max: [152.9 193.3]
Note: SciPy assumes you already know the basics of NumPy arrays: creating them, indexing, slicing and element-wise maths. If those are new to you, work through a NumPy course first, then come back here.
Test yourself
Which library is SciPy built on top of?
- pandas
- NumPy
- Matplotlib
- TensorFlow
Which subpackage would you use to minimize a function?
- scipy.stats
- scipy.signal
- scipy.optimize
- scipy.spatial
Why do the examples in this course use np.random.default_rng(42)?
- It makes the code run faster
- It produces the same 'random' numbers every run, so output is reproducible
- SciPy requires the number 42
- It disables randomness completely