NumPy is the numerical foundation of Python data work. pandas is built on it, scikit-learn uses it, and many plotting libraries expect it. You can get a lot done with pandas alone, but understanding NumPy makes everything above it make more sense.
Arrays vs lists
A Python list can hold anything, and maths on it means looping. A NumPy array holds values of one type and does maths on all of them at once.
import numpy as np
prices = [120, 250, 90]
[p * 1.18 for p in prices] # list: loop needed
arr = np.array([120, 250, 90])
arr * 1.18 # array: one expressionThis "vectorised" style is shorter, and on large data it is dramatically faster because the loop runs in optimised compiled code.
Creating arrays
np.array([1, 2, 3])
np.zeros(5)
np.ones((2, 3))
np.arange(0, 10, 2) # 0, 2, 4, 6, 8
np.linspace(0, 1, 5) # five evenly spaced valuesInspect them with .shape, .ndim, .size and .dtype.
Indexing, slicing and masks
sales = np.array([320, 150, 480, 90, 610, 275])
sales[0], sales[-1], sales[1:4]
sales[sales > 300] # boolean mask: values above 300
sales[(sales > 100) & (sales < 500)]Masks are the NumPy version of filtering, and exactly the same idea appears in pandas.
For 2D arrays (rows and columns):
m = np.array([[10, 20, 30], [40, 50, 60]])
m[1, 2] # row 1, column 2 โ 60
m[:, 0] # first column
m[0, :] # first rowStatistics
sales.sum(), sales.mean(), np.median(sales), sales.std()
sales.min(), sales.max(), sales.argmax() # argmax: position of the max
np.percentile(sales, [25, 50, 75])On 2D arrays, axis controls direction: m.sum(axis=0) sums each column, m.sum(axis=1) sums each row.
Broadcasting
NumPy can combine arrays of different but compatible shapes:
units = np.array([[3, 5, 2], # store A: units of 3 products
[1, 4, 6]]) # store B
price = np.array([100, 40, 250]) # price of each product
revenue = units * price # price is "broadcast" across both rowsThe 1D price array is applied to every row automatically.
Useful extras
np.where(condition, a, b): vectorised if-else, very common in pandas code.np.round,np.abs,np.log,np.sqrt.np.unique(arr, return_counts=True): unique values and their counts.np.random.default_rng(42): reproducible random numbers for simulations.
How NumPy connects to pandas and ML
- A pandas column is backed by a NumPy array (
df["col"].to_numpy()). - scikit-learn models take NumPy arrays (or DataFrames) as input.
- Ideas like masks, axis and broadcasting appear everywhere.
Practise
Our NumPy track goes from creating arrays through masks, statistics and broadcasting to business problems solved with arrays.
Practise what you just read
Reading helps; writing the code yourself is what sticks. Start here: