Artificial Intelligence — Level 2: Data Science & Machine Learning with Python
Get Started Free
Free preview
NumPy arrays
Lecture notes
NumPy provides the ndarray: a fast, fixed-type, multi-dimensional array. Every major ML library (pandas, scikit-learn, TensorFlow, PyTorch) builds on the same ideas.
Creating arrays
import numpy as np
a = np.array([12, 15, 9, 18]) # 1-D
m = np.array([[1, 2, 3], [4, 5, 6]]) # 2-D, shape (2, 3)
print(m.shape, m.ndim, m.dtype) # (2, 3) 2 int64
np.zeros((3, 4)); np.ones(5)
np.arange(0, 10, 2) # [0 2 4 6 8]
np.linspace(0, 1, 5) # 5 evenly spaced values
np.random.default_rng(42).normal(size=(100,)) # reproducible random numbers
m.reshape(3, 2)
Vectorised operations
Operations apply to every element without Python loops — much faster:
prices = np.array([1500, 2500, 4000])
prices * 1.1925 # add VAT to all
prices > 2000 # [False True True]
prices[prices > 2000] # boolean indexing: [2500 4000]
Indexing and slicing
m[0, 2] # row 0, column 2 → 3
m[:, 1] # all rows, column 1 → [2 5]
m[1, :] # second row
Aggregations and axes
m.sum() # 21
m.mean(axis=0) # mean of each column → [2.5 3.5 4.5]
m.max(axis=1) # max of each row → [3 6]
axis=0 works down the rows (per column); axis=1 across columns (per row).
Broadcasting
NumPy stretches compatible shapes automatically: subtracting a row of column means from a matrix (m - m.mean(axis=0)) centres every column — a common preprocessing step.
Want to go further?
18 h · Enroll to access every lesson and earn the certificate.