NumPy
NumPy
Arrays, operations, broadcasting, linear algebra, and random — complete NumPy reference.
📖 5 sections
⏰ 15 min read
✅ Quizzes included
01Array Basics
NUMPYCreating arrays
import numpy as np

np.array([1,2,3])          # 1D array
np.array([[1,2],[3,4]])    # 2D array
np.zeros((3,4))            # zeros matrix 3x4
np.ones((2,3))             # ones matrix
np.eye(3)                  # 3x3 identity matrix
np.arange(0,10,2)          # [0,2,4,6,8]
np.linspace(0,1,5)         # 5 evenly spaced 0 to 1
np.random.rand(3,3)        # random 3x3 (uniform)
np.random.randn(3,3)       # random 3x3 (normal dist)
02Array Properties & Indexing
NUMPYShape, dtype, indexing
a = np.array([[1,2,3],[4,5,6]])
a.shape    # (2,3)
a.ndim     # 2
a.size     # 6
a.dtype    # dtype(int64)

# Indexing
a[0,1]       # 2  (row 0, col 1)
a[1,:]       # [4,5,6]  (row 1)
a[:,0]       # [1,4]  (col 0)
a[0:2,1:3]  # slicing: rows 0-1, cols 1-2
a[a>3]       # boolean indexing: [4,5,6]
03Operations & Math
NUMPYArray operations
a = np.array([1,2,3])
b = np.array([4,5,6])

a + b      # [5,7,9]  element-wise
a * b      # [4,10,18]  element-wise
a ** 2     # [1,4,9]  power
np.dot(a,b)  # 32  dot product

# Matrix multiplication
A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])
A @ B      # matrix multiply
np.matmul(A,B)  # same

np.sum(a)       # 6
np.mean(a)      # 2.0
np.std(a)       # 0.816
np.max(a)       # 3
np.argmax(a)    # 2 (index of max)
04Broadcasting
NUMPYBroadcasting rules
# Arrays broadcast when shapes are compatible:
# (3,4) + (4,) -> broadcast (4,) to (3,4)

a = np.array([[1,2,3],[4,5,6]])  # shape (2,3)
b = np.array([10,20,30])         # shape (3,)
a + b  # [[11,22,33],[14,25,36]]

# Column broadcast
c = np.array([[1],[2]])  # shape (2,1)
a + c  # [[2,3,4],[6,7,8]]

# Rule: dimensions must be equal OR one must be 1
💡
When shapes conflict, NumPy tries to expand dimensions of size 1. Shapes (3,4) and (1,4) are compatible. (3,4) and (2,4) are not.
05Linear Algebra
NUMPYLA operations
A = np.array([[1,2],[3,4]])

np.linalg.det(A)      # determinant: -2.0
np.linalg.inv(A)      # inverse matrix
np.linalg.eig(A)      # eigenvalues, eigenvectors
np.linalg.norm(A)     # matrix norm
np.linalg.solve(A,b)  # solve Ax=b

# Decompositions
U,S,Vt = np.linalg.svd(A)  # SVD
Q,R = np.linalg.qr(A)      # QR decomposition
❓ Quiz
How do you create a 3x3 identity matrix in NumPy?
np.eye(n) creates an n x n identity matrix with 1s on the diagonal and 0s elsewhere. np.identity(n) also works.