NumPy Cheat Sheet
Free NumPy cheat sheet: the most-used NumPy syntax and methods at a glance — searchable and beginner-friendly.
Creating Arrays
| Concept | Syntax | Example |
|---|---|---|
| Import numpy The universal alias — every snippet assumes np. | import numpy as np | import numpy as np |
| From a list Nest lists for 2D: np.array([[1, 2], [3, 4]]). | np.array([...]) | a = np.array([1, 2, 3]) |
| Zeros / ones Pass a tuple for multi-dimensional shapes. | np.zeros(shape) / np.ones(shape) | np.zeros((2, 3)) |
| Range Like Python range() but returns an array, stop-exclusive. | np.arange(start, stop, step) | np.arange(0, 10, 2) # [0 2 4 6 8] |
| Evenly spaced Great for plotting axes — endpoint is included. | np.linspace(start, stop, num) | np.linspace(0, 1, 5) # 5 points incl. endpoints |
| Identity / full np.eye makes an identity matrix; np.full fills a constant. | np.eye(n) / np.full(shape, val) | np.full((2, 2), 7) |
Inspecting
| Concept | Syntax | Example |
|---|---|---|
| Shape A tuple of dimension sizes. | arr.shape | a.shape # (3, 4) |
| Number of dimensions How many axes the array has. | arr.ndim | a.ndim # 2 |
| Total elements Product of all the dimension sizes. | arr.size | a.size # 12 |
| Data type Cast with a.astype(np.float64). | arr.dtype | a.dtype # dtype('int64') |
| Item byte size Bytes per element — useful for memory tuning. | arr.itemsize | a.itemsize # 8 bytes for int64 |
Indexing & Slicing
| Concept | Syntax | Example |
|---|---|---|
| Element access Comma-separated indices for each axis. | arr[i, j] | a[0, 2] |
| Slicing Works per axis: a[0:2, 1:3] slices rows and columns. | arr[start:stop:step] | a[1:5:2] |
| Boolean masking Select all elements matching a condition. | arr[mask] | a[a > 5] |
| Fancy indexing Index with a list/array of positions. | arr[[i1, i2, ...]] | a[[0, 2, 4]] |
| Conditional replace Vectorized if/else across the array. | np.where(cond, x, y) | np.where(a > 0, a, 0) # clamp negatives to 0 |
Math & Aggregation
| Concept | Syntax | Example |
|---|---|---|
| Element-wise math Operations broadcast across the whole array. | arr + n, arr * arr2 | a * 2 + 1 |
| Sum axis=0 collapses rows, axis=1 collapses columns. | arr.sum(axis=None) | a.sum(axis=0) # sum down each column |
| Mean / std np.median(a) for the median. | arr.mean() / arr.std() | a.mean(axis=1) |
| Min / max argmin()/argmax() give the index of the extreme. | arr.min() / arr.max() | a.max() |
| Universal functions Vectorized math applied element-wise. | np.sqrt, np.exp, np.sin | np.sqrt(a) |
| Cumulative Running totals and products. | np.cumsum / np.cumprod | np.cumsum([1, 2, 3]) # [1 3 6] |
Reshaping & Stacking
| Concept | Syntax | Example |
|---|---|---|
| Reshape Use -1 to infer one dimension: a.reshape(-1, 2). | arr.reshape(rows, cols) | a.reshape(3, 4) |
| Flatten ravel returns a view when possible; flatten always copies. | arr.ravel() / arr.flatten() | a.ravel() |
| Transpose Swaps axes — rows become columns. | arr.T | a.T |
| Stack vertically / horizontally Glue arrays along rows or columns. | np.vstack / np.hstack | np.vstack([a, b]) |
| Concatenate General-purpose joining along a chosen axis. | np.concatenate([a, b], axis=0) | np.concatenate([a, b], axis=1) |
| Add an axis Reshape a 1D array into 2D for broadcasting. | arr[:, np.newaxis] | a[:, np.newaxis] # column vector |
Linear Algebra & Random
| Concept | Syntax | Example |
|---|---|---|
| Dot product The @ operator is matrix multiplication. | np.dot(a, b) / a @ b | a @ b |
| Matrix inverse Square, non-singular matrices only. | np.linalg.inv(m) | np.linalg.inv(m) |
| Determinant Zero determinant means the matrix is not invertible. | np.linalg.det(m) | np.linalg.det(m) |
| Random seed Makes random output reproducible. | np.random.seed(n) | np.random.seed(42) |
| Random floats randn() draws from a standard normal distribution. | np.random.rand(shape) | np.random.rand(3, 2) # uniform [0,1) |
| Random integers high is exclusive. | np.random.randint(low, high, size) | np.random.randint(0, 10, size=5) |