Create arrays
An array holds values of one type in a grid of any number of dimensions.
| Task | Code |
|---|
| Import NumPy | import numpy as np |
| From a list | np.array([1, 2, 3]) |
| 2D from nested lists | np.array([[1, 2, 3], [4, 5, 6]]) |
| Zeros, ones, one fill value | np.zeros((2, 3)), np.ones(4), np.full((2, 2), 7) |
| Range with a step (end excluded) | np.arange(0, 10, 2) # [0 2 4 6 8] |
| n evenly spaced points (end included) | np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1.] |
| Identity matrix | np.eye(3) |
| Same shape as another array | np.zeros_like(m), np.ones_like(m) |
| Choose the element type | np.array([1, 2, 3], dtype=np.float32) |
| Coordinate grids | xx, yy = np.meshgrid(np.arange(3), np.arange(2)) |
Inspect an array
| Task | Code |
|---|
| Shape: size of each dimension | m.shape # (3, 4) |
| Number of dimensions | m.ndim # 2 |
| Number of elements | m.size # 12 |
| Element type | m.dtype # int64 |
| Convert the type | m.astype(np.float64) |
| Length of the first dimension | len(m) # 3 |
| Back to a Python list | m.tolist() |
| Print fewer decimals | np.set_printoptions(precision=3, suppress=True) |
Index and slice
Slices are views: they share memory with the original array. Masks and index lists return copies.
| Task | Code |
|---|
| First and last element | a[0], a[-1] |
| Slice start:stop (stop excluded) | a[1:4] # [20 30 40] |
| Every second element, reversed | a[::2], a[::-1] |
| One element of a 2D array | m[1, 2] # 6 |
| A row, a column | m[0], m[:, 1] |
| A block of rows and columns | m[:2, 1:3] |
| Elements that match a condition | a[a > 25] # [30 40 50] |
| Combine conditions | a[(a > 15) & (a < 45)] |
| Pick by a list of positions | a[[0, 2, 4]] |
| Positions that match | np.flatnonzero(a > 25) # [2 3 4] |
| Choose per element | np.where(a > 25, a, 0) |
| Copy before changing a slice | part = a[1:3].copy() |
| Set values with a mask | a[a > 40] = 0 |
Math and broadcasting
Operators work element by element. Broadcasting stretches a scalar, row or column to match the other array's shape.
| Task | Code |
|---|
| Element-wise arithmetic | x + y, x - y, x * y, x / y, x ** 2 |
| With a scalar | x * 10 |
| Square root, exponent, log | np.sqrt(x), np.exp(x), np.log(x) |
| Absolute value, rounding | np.abs(x - 5), np.round(x / 3, 2) |
| Limit values to a range | np.clip(x, 2, 8) |
| Element-wise maximum | np.maximum(x, 3) |
| Dot product | x @ y # 37.0 |
| Center each column (broadcast a row) | m - m.mean(axis=0) |
| Scale each row (broadcast a column) | m / m.sum(axis=1, keepdims=True) |
| Compare floats safely | np.isclose(0.1 + 0.2, 0.3) # True, np.allclose(x, y) |
| Trigonometry and pi | np.sin(np.pi / 2) # 1.0 |
Aggregate along an axis
axis=0 works down the rows and gives one result per column. axis=1 works across the columns and gives one result per row.
| Task | Code |
|---|
| Total of all elements | m.sum() # 21 |
| One result per column | m.sum(axis=0) # [5 7 9] |
| One result per row | m.sum(axis=1) # [ 6 15] |
| Mean and standard deviation | m.mean(), m.std(), m.mean(axis=0) |
| Minimum, maximum | m.min(), m.max(axis=1) |
| Position of the maximum | m.argmax(), m.argmax(axis=1) |
| Median and percentiles | np.median(m), np.percentile(m, [25, 50, 75]) |
| Running total | np.cumsum(m, axis=1) |
| Product of all elements | m.prod() # 720 |
| Any, all, count | (m > 4).any(), (m > 0).all(), np.count_nonzero(m > 2) |
Reshape and combine
A reshape keeps the elements and changes the shape, so the total size must stay the same.
| Task | Code |
|---|
| New shape | a.reshape(2, 3) |
| Let NumPy work out one size | a.reshape(3, -1), a.reshape(-1, 1) |
| Flatten to 1D | m.ravel(), m.flatten() |
| Transpose | m.T |
| Add a dimension | a[:, np.newaxis], np.expand_dims(a, axis=0) |
| Drop dimensions of size 1 | np.squeeze(np.ones((1, 3, 1))) |
| Join along an existing axis | np.concatenate([a, a]) |
| Stack rows or columns | np.vstack([m, m]), np.hstack([m, m]) |
| 1D arrays as columns | np.column_stack([a, a ** 2]) |
| Stack along a new axis | np.stack([a, a], axis=0) # shape (2, 6) |
| Split into pieces | np.split(a, 3), np.array_split(a, 4) |
| Repeat or tile | np.repeat([1, 2], 2) # [1 1 2 2], np.tile([1, 2], 2) # [1 2 1 2] |
Sort, search and unique values
| Task | Code |
|---|
| Sorted copy | np.sort(a) |
| Largest first | np.sort(a)[::-1] |
| Positions that would sort | np.argsort(a) |
| Three largest values | np.sort(a)[-3:] |
| Unique values and their counts | values, counts = np.unique(a, return_counts=True) |
NumPy 2 names (unique_values may be unsorted) | np.unique_values(a), np.unique_counts(a) |
| Is each element in a list? | np.isin(a, [1, 9]) |
| Insert position in a sorted array | np.searchsorted([1, 3, 5, 7], 4) # 2 |
| Set operations | np.intersect1d(a, [1, 2, 10]), np.union1d(a, [10]), np.setdiff1d(a, [1]) |
| Sort rows by one column | m[m[:, 1].argsort()] |
Random numbers
Create one seeded Generator and draw everything from it, so results repeat run after run.
| Task | Code |
|---|
| Seeded generator | rng = np.random.default_rng(42) |
| Floats in [0, 1) | rng.random(3) |
| Integers, high end excluded | rng.integers(1, 7, size=10) |
| Normal distribution | rng.normal(loc=0, scale=1, size=(2, 3)) |
| Uniform floats in a range | rng.uniform(5, 10, size=4) |
| Pick from a list | rng.choice(["a", "b", "c"], size=5) |
| Pick without repeats | rng.choice(10, size=3, replace=False) |
| Pick with weights | rng.choice(["H", "T"], size=10, p=[0.7, 0.3]) |
| Shuffled copy, shuffle in place | rng.permutation(a), rng.shuffle(a) |
| Binomial and Poisson counts | rng.binomial(10, 0.5, size=5), rng.poisson(3, size=5) |
Linear algebra
| Task | Code |
|---|
| Matrix product | A @ A |
| Solve Ax = b | np.linalg.solve(A, b) # [0.8 1.4] |
| Inverse and determinant | np.linalg.inv(A), np.linalg.det(A) |
| Vector length | np.linalg.norm(b) |
| Eigenvalues and eigenvectors | values, vectors = np.linalg.eig(A) |
| Fit a straight line | slope, intercept = np.polyfit(x, y, 1) |
| Outer product | np.outer([1, 2], [3, 4]) |
| Diagonal and trace | np.diag(A), np.trace(A) |
Missing and special values
np.nan marks a missing float. Any arithmetic with it gives nan, so use the nan functions or a mask.
| Task | Code |
|---|
| Missing value | np.nan |
| Find missing values | np.isnan(v), np.isnan(v).sum() |
| Drop missing values | v[~np.isnan(v)] |
| Replace missing and infinite values | np.nan_to_num(v, nan=0.0, posinf=0.0) |
| Infinity and finite checks | np.inf, np.isfinite(v) |
| Statistics that skip NaN | np.nanmean(v[:3]) # 2.0, np.nanmax(v) |
Save and load
| Task | Code |
|---|
| One array, binary file | np.save("data.npy", m), m = np.load("data.npy") |
| Several arrays in one file | np.savez("data.npz", x=x, y=y), np.load("data.npz")["x"] |
| Write CSV text | np.savetxt("data.csv", m, delimiter=",", fmt="%d") |
| Read CSV text | np.loadtxt("data.csv", delimiter=",") |
NumPy 2: old names and what to write now
NumPy 2 removed many aliases, so code copied from older tutorials can fail with an AttributeError.
| Task | NumPy 2 | Old form |
|---|
| Missing value | np.nan | np.NaN |
| Infinity | np.inf | np.Inf |
| 64-bit float type | np.float64 | np.float_ |
| Area under a curve | np.trapezoid(y, x) | np.trapz(y, x) |
| Is each element in another array? | np.isin(a, b) | np.in1d(a, b) |
| Stack rows | np.vstack([a, a]) | np.row_stack([a, a]) |
| Product | np.prod(a) | np.product(a) |
| Random numbers | rng = np.random.default_rng(0)
rng.random(3) | np.random.seed(0)
np.random.rand(3) |
The NumPy calls that data science code is built on, grouped by task: create arrays, inspect them, index and slice, do element-wise math, aggregate along an axis, reshape and combine, sort and search, draw random numbers, and solve linear algebra. Each row is a short snippet you can paste, plus one line on what it does.
Everything here is written for NumPy 2, the version Coddy runs, and the last table lists the names NumPy 2 removed, next to what to write instead. Most examples use a = np.array([3, 1, 4, 1, 5, 9, 2, 6]) and m = np.arange(12).reshape(3, 4). New to Python itself? Start with the Python cheat sheet and the Python playground, and keep the pandas, Matplotlib and scikit-learn cheat sheets next to this one.