NumPy Cheat Sheet
The whole NumPy course on one page — creation, attributes, indexing, statistics, reshaping, combining, broadcasting, random, linear algebra, file I/O and performance — in quick-reference tables.
This page summarises everything in the NumPy course. Keep it open while you practise, and use it for revision before interviews. Every row links back to a concept you have already studied in detail.
Definition
NumPy (Numerical Python) is the core Python library for fast numerical computing. Its central object, the
ndarray, is an N-dimensional, fixed-size, homogeneous (single-dtype) array stored in contiguous memory, with vectorised operations implemented in C.
python
import numpy as np # the universal convention1. Creating arrays
| Code | Result / meaning |
|---|---|
np.array([1, 2, 3]) | from a list → [1 2 3] |
np.array([[1, 2], [3, 4]]) | 2D array (2 × 2) |
np.zeros((2, 3)) / np.ones(4) | filled with 0. / 1. (float) |
np.full((2, 2), 7) | filled with 7 |
np.empty(3) | uninitialised (garbage values) — fast |
np.arange(0, 10, 2) | [0 2 4 6 8] — stop excluded |
np.linspace(0, 1, 5) | [0. 0.25 0.5 0.75 1.] — 5 evenly spaced, stop included |
np.eye(3) / np.identity(3) | identity matrix |
np.zeros_like(a) / np.ones_like(a) | same shape & dtype as a |
2. Attributes & dtypes
| Code | Meaning |
|---|---|
a.shape | tuple of dimension sizes, e.g. (2, 3) |
a.ndim | number of dimensions |
a.size | total number of elements |
a.dtype | element type: int64, float64, bool, uint8, <U5 … |
a.itemsize / a.nbytes | bytes per element / total bytes |
a.astype(np.float32) | converted copy |
3. Indexing & slicing
| Code | Selects |
|---|---|
a[0], a[-1] | first / last element (1D) or row (2D) |
a[1, 2] | row 1, column 2 |
a[1:4], a[::2], a[::-1] | slice, every 2nd, reversed |
a[:, 0] / a[0, :] | first column / first row |
a[a > 50] | boolean mask → 1D array of matches |
a[(a > 10) & (a < 50)] | combine conditions with &, |, ~ and brackets |
a[[0, 2]] | fancy indexing: rows 0 and 2 (copy) |
np.where(a > 50, 1, 0) | conditional replace |
Remember: slices are views (share memory), boolean/fancy indexing returns copies. Use
.copy()when you need independence.
4. Maths & statistics
| Code | Meaning |
|---|---|
a + b, a * 2, a ** 2, np.sqrt(a) | element-wise (ufuncs) |
a.sum(), a.mean(), np.median(a) | totals and averages |
a.std(), a.var() | spread (population; ddof=1 for sample) |
a.min(), a.max(), a.argmin(), a.argmax() | extremes / their positions |
a.sum(axis=0) | down the rows → one value per column |
a.sum(axis=1) | across the columns → one value per row |
np.cumsum(a), np.cumprod(a) | running total / running product |
np.sort(a), np.argsort(a), np.unique(a) | sorted copy / sort order / distinct values |
np.round(a, 2), np.clip(a, 0, 100) | round / limit range |
np.nanmean(a), np.isnan(a) | ignore / detect missing values |
text
axis=1 →
axis=0 [[3 1 2] sum(axis=0) = [9 6 6] (per column)
↓ [6 5 4]] sum(axis=1) = [6 15] (per row)5. Reshaping
| Code | Meaning |
|---|---|
a.reshape(3, 2) / a.reshape(-1, 2) | new shape, same elements; -1 = "work it out" |
a.ravel() | flatten to 1D — view when possible |
a.flatten() | flatten to 1D — always a copy |
a.T / np.transpose(a) | swap rows and columns |
a[:, np.newaxis] / np.expand_dims(a, 1) | add a dimension (1D → column) |
np.squeeze(a) | remove size-1 dimensions |
6. Combining & splitting
| Code | Meaning |
|---|---|
np.concatenate([a, b], axis=0) | join along an existing axis |
np.vstack([a, b]) | stack vertically (add rows) |
np.hstack([a, b]) | stack horizontally (add columns) |
np.stack([a, b]) | join along a new axis |
np.split(a, 3), np.vsplit, np.hsplit | split into pieces |
7. Broadcasting rules
Compare shapes from the right; two dimensions are compatible if they are equal or one of them is 1. Missing dimensions on the left count as 1.
| Shapes | Result |
|---|---|
(3, 4) and (4,) | ✅ (3, 4) — row added to every row |
(3, 4) and (3, 1) | ✅ (3, 4) — column added to every column |
(3, 1) and (1, 4) | ✅ (3, 4) — outer combination |
(3, 4) and (3,) | ❌ error — 4 vs 3; use b[:, None] |
8. Random numbers
| Legacy | Modern Generator | Gives |
|---|---|---|
np.random.seed(42) | rng = np.random.default_rng(42) | reproducibility |
np.random.rand(2, 3) | rng.random((2, 3)) | uniform floats [0, 1) |
np.random.randn(5) | rng.standard_normal(5) | standard normal |
np.random.randint(1, 7, 5) | rng.integers(1, 7, 5) | integers, high excluded |
np.random.normal(35, 12, 5) | rng.normal(35, 12, 5) | bell curve (mean, std) |
np.random.uniform(0, 10, 5) | rng.uniform(0, 10, 5) | uniform floats in a range |
np.random.binomial(14, 0.6, 5) | rng.binomial(14, 0.6, 5) | successes in n trials |
np.random.choice(a, 3, replace=False, p=w) | rng.choice(a, 3, replace=False, p=w) | sample from items |
np.random.shuffle(a) / permutation(a) | rng.shuffle(a) / rng.permutation(a) | in place / copy |
9. Linear algebra
| Code | Meaning |
|---|---|
A * B | element-wise product |
A @ B, np.matmul(A, B), np.dot(A, B) | matrix product: (m, n) @ (n, p) → (m, p) |
a @ b (1D) | dot product → one number |
np.linalg.inv(A) | inverse (A @ A_inv = I) |
np.linalg.det(A) | determinant (0 → singular, no inverse) |
np.linalg.solve(A, b) | solve A x = b |
np.linalg.norm(v) | vector length; norm(a - b) = distance |
np.allclose(X, Y) | compare floats with tolerance |
10. Images
| Code | Meaning |
|---|---|
(H, W) / (H, W, 3), dtype uint8 | grayscale / colour image, values 0–255 |
rgb @ [0.299, 0.587, 0.114] | colour → grayscale |
img[r1:r2, c1:c2] | crop |
img[::-1], img[:, ::-1], np.rot90(img, k) | flip vertical / horizontal, rotate |
np.clip(img.astype(np.int16) + 50, 0, 255).astype(np.uint8) | safe brightness |
255 - img, np.where(img > 127, 255, 0) | invert, threshold |
11. Saving & loading
| Code | Meaning |
|---|---|
np.save("a.npy", a) / np.load("a.npy") | one array, binary, exact |
np.savez("d.npz", x=a, y=b) / np.savez_compressed | many named arrays |
np.savetxt("a.csv", a, fmt="%d", delimiter=",") | human-readable text |
np.loadtxt("a.csv", delimiter=",", skiprows=1) | clean numeric text |
np.genfromtxt("a.csv", delimiter=",", skip_header=1) | text with missing values → nan |
12. Performance rules
- No Python loops over array elements — use ufuncs, masks,
np.where, broadcasting. - No
np.appendin loops — preallocate or collect in a list and convert once. - Use NumPy aggregations (
a.sum()), not Python'ssum(). - Prefer views (slicing,
ravel,reshape) over copies on big data;.copy()when you must protect the original. - Pick the smallest suitable dtype (
uint8images,float32for ML).
Example — the course in ten lines
python
import numpy as np
a = np.array([[3, 1, 2], [6, 5, 4]])
print(a.shape, a.ndim, a.size, a.dtype)
print(a.sum(), a.sum(axis=0), a.sum(axis=1))
print(a.mean(), a.max(axis=1), a.argmax(axis=1))
print(a.reshape(3, 2).tolist(), a.ravel().tolist())
print(np.sort(a, axis=1).tolist())
print(a[a > 2])
print(np.vstack([a, [7, 8, 9]]).shape, np.hstack([a, a]).shape)
print(a + np.array([10, 20, 30]))
print(a @ a.T)text
(2, 3) 2 6 int64
21 [9 6 6] [ 6 15]
3.5 [3 6] [0 0]
[[3, 1], [2, 6], [5, 4]] [3, 1, 2, 6, 5, 4]
[[1, 2, 3], [4, 5, 6]]
[3 6 5 4]
(3, 3) (2, 6)
[[13 21 32]
[16 25 34]]
[[14 31]
[31 77]]Common mistakes (whole course)
- ❌
np.array([1, "2"])and expecting numbers. ✅ Arrays are homogeneous — everything became a string. - ❌
and/orwith arrays. ✅&/|with brackets:(a > 1) & (a < 5). - ❌ Confusing
axis=0(per column) andaxis=1(per row). ✅ The axis you name is the one that disappears. - ❌ Editing a slice and being surprised the original changed. ✅ Slices are views;
.copy(). - ❌
*when you meant@. ✅*is element-wise,@is matrix multiplication. - ❌ uint8 overflow in image maths. ✅ Widen → compute → clip → narrow.
Interview tip
Q: Why is NumPy faster than Python lists? A: An ndarray stores one dtype in contiguous memory, so operations run as tight compiled C loops (often SIMD-accelerated) without per-element type checks or Python object overhead. Python lists store pointers to separate objects scattered in memory, and every operation goes through the interpreter.
Key points to remember
- The ndarray is an N-dimensional, fixed-size, single-dtype array in contiguous memory with vectorised C operations.
- Create with array, zeros, ones, full, arange (stop excluded), linspace (stop included), eye.
- axis=0 aggregates down the rows (per column); axis=1 across the columns (per row).
- Slices and reshape/ravel are views; boolean/fancy indexing and flatten are copies.
- Broadcasting compares shapes from the right: sizes must be equal or 1.
- Use default_rng for random numbers, @ for matrix products, np.linalg for inverse/solve/norm.
- Save with np.save/np.savez (binary) or np.savetxt (text); load with np.load/loadtxt/genfromtxt.
- Performance: vectorise, never np.append in a loop, use NumPy aggregations.
Try it yourself
The course in ten lines
Mini project: IPL season report
Practice: build your own cheat-sheet check
Revision Flashcards
Tap a card to flip it and see the answer.
