SciPy Introduction
SciPy is a collection of scientific tools for Python, built on NumPy arrays.
What is SciPy?
- SciPy stands for Scientific Python
- It was started in 2001 and is free and open source
- It uses NumPy arrays and adds algorithms for maths, science and engineering
- Many parts are written in C and Fortran, so they are fast
NumPy or SciPy?
| NumPy | SciPy |
|---|---|
| Arrays and basic maths | Advanced scientific algorithms |
| Mean, sum, sorting | Statistical tests, distributions |
| Matrix multiplication | Optimization, integration, interpolation |
| Needed by SciPy | Needs NumPy |
You almost always use them together.
Installing SciPy
Example
bash
pip install scipyThis also installs NumPy if you do not have it.
SciPy is already included in Anaconda and Google Colab.
Importing SciPy
SciPy is organised into sub-modules. You import the part you need, not the whole library:
Example
python
from scipy import stats
import numpy as np
marks = np.array([65, 72, 78, 80, 85, 88, 90, 92, 72, 95])
print(stats.mode(marks).mode)Output
72
Here we imported only the stats module and used it to find the most common value.
Checking the Version
Example
python
import scipy
print(scipy.__version__)Output
1.18.1
Your version may be different. Version 1.11 or newer works for this tutorial.
The Main Modules
| Module | Used for |
|---|---|
scipy.constants | Physical and maths constants, unit conversion |
scipy.stats | Statistics, distributions, hypothesis tests |
scipy.optimize | Finding minimums, maximums and roots, curve fitting |
scipy.interpolate | Estimating values between known data points |
scipy.integrate | Calculating areas under curves (integrals) |
scipy.linalg | Linear algebra: solving equations with matrices |
scipy.signal | Signal processing (audio, sensors) |
scipy.spatial | Distances and geometry |
A Quick Taste: Solving Equations
Solve these two equations together:
- 2x + y = 11
- x - y = 1
Example
python
import numpy as np
from scipy import linalg
A = np.array([[2, 1], [1, -1]])
b = np.array([11, 1])
print(linalg.solve(A, b))Output
[4. 3.]
So x = 4 and y = 3. Check: 2(4) + 3 = 11 and 4 - 3 = 1.
Exercise
Exercise
Which SciPy module would you use for statistical tests?
