Python Tutorial
SciPy Introduction
SciPy builds on NumPy with algorithms for optimization, statistics, interpolation, sparse matrices, and signal processing.
What Is SciPy?
Each domain lives in a submodule: scipy.optimize, scipy.stats, scipy.interpolate, scipy.sparse, scipy.signal, scipy.constants.
Chapters in This Section
| Chapter | You will learn |
|---|---|
| Getting Started | Install and import |
| Constants | Scientific constants |
| Optimizers | Minimize and curve_fit |
| Sparse Data | CSR matrices |
| Interpolation | interp1d and griddata |
| Statistics | Distributions and tests |
| Signal | Filters and peaks |
What SciPy Adds on Top of NumPy
SciPy builds on NumPy arrays and provides submodules for scientific computing. Import the specific submodule you need.
| Submodule | For |
|---|---|
scipy.stats | Distributions, tests, correlations |
scipy.optimize | Root finding, curve fitting, minimization |
scipy.interpolate | Interpolation of data points |
scipy.linalg | Advanced linear algebra |
scipy.integrate | Numerical integration, ODEs |
Quick Examples
from scipy import stats, optimize
# a t-test between two samples
a = [20, 22, 19, 24, 25]
b = [28, 30, 27, 26, 29]
t, p = stats.ttest_ind(a, b)
print(f"p-value = {p:.4f}") # small p -> groups differ
# find a root of x^2 - 2 (i.e. sqrt 2)
root = optimize.brentq(lambda x: x**2 - 2, 0, 2)
print(root) # 1.4142135...Try It Yourself
Exercise 1: Use scipy.stats to compute the mean and standard deviation summary of [4, 8, 15, 16, 23, 42].
Show solution
from scipy import stats
print(stats.describe([4, 8, 15, 16, 23, 42]))Exercise 2: Minimize f(x) = (x - 3)**2 and print the x that minimizes it.
Show solution
from scipy.optimize import minimize_scalar
res = minimize_scalar(lambda x: (x - 3)**2)
print(round(res.x, 3)) # 3.0Key Takeaways
- SciPy extends NumPy with scientific submodules.
- Import the submodule you need (
stats,optimize, …). - It covers statistics, optimization, interpolation, and linear algebra.