23. NumPy — Cheat sheet
The essentials of module 23 on one page. Every runnable block on this page is checked against its output. All blocks run in order and share the setup below.
import numpy as np
np.set_printoptions(precision=3, suppress=True) # display only; values unchangedsales = np.array([[40722, 45357, 52453, 82368], # S01: 2024 revenue by quarter [21926, 27811, 33103, 58803], # S02 [16664, 34934, 24725, 38865]]) # S03temps = np.array([20.21, 22.3, np.nan, 24.52, 38.03])Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| make an array from a list | np.array(seq) |
np.array([20.2, 22.3]) |
| make a range of numbers | np.arange, np.linspace |
np.linspace(19, 23, 5) |
| make a placeholder | np.zeros, np.ones, np.full, np.empty |
np.full(4, np.nan) |
| see the size and type | .shape, .ndim, .size, .dtype, .nbytes |
sales.shape → (3, 4) |
| change the dtype | .astype(dtype) (always a copy) |
x.astype(np.float32) |
| load a numeric CSV with gaps | np.genfromtxt |
usecols=(2, 3), skip_header=1 |
| load a clean CSV fast | np.loadtxt |
dtype=str for text columns |
| save and load arrays | np.save / np.load, np.savez_compressed |
np.save("out.npy", a) |
| take a row, column, block | a[i], a[:, j], a[r0:r1, c0:c1] |
sales[:, 3] |
| keep values that pass a test | boolean mask | a[a > 30] |
| combine tests | &, |, ~ with parentheses |
(t > 30) & (v > 4.5) |
| count or share of matches | mask.sum(), mask.mean() |
(t > 30).mean() |
| pick rows in a given order | fancy indexing | a[[2, 0]] |
| sort values / get the sort order | np.sort, np.argsort |
np.argsort(x)[::-1][:3] |
| aggregate per column / per row | axis=0 / axis=1 |
sales.sum(axis=1) |
| keep the reduced axis for broadcasting | keepdims=True |
a / a.sum(axis=1, keepdims=True) |
| ignore missing values | np.nanmean, np.nanmax, … |
np.nanmean(temps) |
| find missing values | np.isnan |
np.isnan(a).sum(axis=0) |
| standardize columns | broadcasting | (X - X.mean(0)) / X.std(0) |
| vectorized if/else | np.where(cond, a, b) |
np.where(t > 30, "hot", "ok") |
| vectorized if/elif/else | np.select(conds, choices, default) |
see Conditional logic |
| cap values | np.clip(a, lo, hi) |
np.clip(p, 0, 1) |
| change the shape | .reshape, .ravel, .T |
a.reshape(-1, 4) |
| join arrays | np.concatenate, np.stack, np.column_stack |
np.column_stack([ones, x]) |
| split an array | np.split, np.array_split |
np.array_split(a, 3) |
| distinct values and counts | np.unique(a, return_counts=True) |
|
| labels to positions | np.unique(a, return_inverse=True) |
then np.add.at or np.bincount |
| matrix product | A @ B |
units @ price |
solve Ax = b |
np.linalg.solve(A, b) |
not inv(A) @ b |
| least-squares fit | np.linalg.lstsq(X, y) |
coef = lstsq(X, y)[0] |
| eigenvalues of a symmetric matrix | np.linalg.eigh(S) |
ascending, real |
| main patterns of any matrix | np.linalg.svd(M, full_matrices=False) |
U, s, Vt |
| reproducible random numbers | rng = np.random.default_rng(42) |
rng.normal(0, 1, 5) |
| compare float arrays | np.allclose(a, b), np.isclose |
not == |
| compare arrays exactly | np.array_equal(a, b) |
equal_nan=True for NaN |
| check for shared memory | np.shares_memory(a, b) |
views share, copies do not |
| print plain Python values | float(x), int(x), .tolist() |
avoids np.float64(...) |
Create arrays
Section titled “Create arrays”| Call | Result |
|---|---|
np.array([[1, 2], [3, 4]]) |
2 × 2 int64 |
np.array([1, 2.5]) |
float64: one float upcasts all |
np.zeros((2, 3)), np.ones(3) |
filled with 0.0 or 1.0 |
np.full(3, np.nan), np.full_like(a, 7) |
filled with a value |
np.empty(5) |
uninitialized memory: fill it before you read it |
np.arange(0, 60, 10) |
[0 10 20 30 40 50], stop excluded |
np.linspace(0, 1, 5) |
5 points, both ends included |
np.eye(3) |
identity matrix |
np.zeros_like(a), np.ones_like(a) |
same shape and dtype as a |
print(sales.shape, sales.ndim, sales.size, sales.dtype, sales.itemsize, sales.nbytes)print(len(sales), temps.shape) # len() = length of axis 0(3, 4) 2 12 int64 8 963 (5,)dtypes and memory
Section titled “dtypes and memory”| dtype | Bytes | Range / precision | Note |
|---|---|---|---|
bool |
1 | True/False |
masks; sum() counts True |
int8 / uint8 |
1 | −128..127 / 0..255 | images use uint8 |
int16 |
2 | ±32,767 | |
int32 |
4 | ±2.1 × 10⁹ | |
int64 |
8 | ±9.2 × 10¹⁸ | default integer |
float32 |
4 | ~7 digits | deep learning |
float64 |
8 | ~15–17 digits | default float |
<U5 |
20 | text, max 5 chars | 4 bytes per character |
object |
8 | any Python object | slow; avoid |
small = np.array([100, 120], dtype=np.int8)print(small + small) # wraps around silentlyprint(small.astype(np.int64) + small) # upcast firstprint(np.iinfo(np.int8).max, np.finfo(np.float32).eps)print(np.array([2.7, -2.7]).astype(int), np.round([2.5, 3.5])) # truncate; half to even[-56 -16][200 240]127 1.1920929e-07[ 2 -2] [2. 4.]- Promotion of two arrays (or NumPy scalars): the smallest dtype that holds both.
int8+int16→int16,int8+float32→float32,int64+float32→float64. - A Python
int/floattakes the array’s dtype when the kind matches:int8_arr + 5staysint8,float32_arr * 2.0staysfloat32. A Python float with an int array →float64. - NumPy 2:
small + 300raisesOverflowError(300 does not fitint8). float32saves half the memory offloat64; check that 7 digits are enough.
Load and save
Section titled “Load and save”data = np.genfromtxt("data/sensors.csv", delimiter=",", skip_header=1, usecols=(2, 3, 4)) # blanks -> nanids = np.loadtxt("data/sensors.csv", delimiter=",", skiprows=1, usecols=1, dtype=str) # strict, fastnp.save("output/clean.npy", data) # binary, keeps shape/dtypedata = np.load("output/clean.npy")np.savez_compressed("output/all.npz", temps=data[:, 0], ids=ids)with np.load("output/all.npz") as f: temps = f["temps"]np.savetxt("output/temps.csv", data, delimiter=",", fmt="%.2f", header="t,h,v")| Reader | Blank cells | Use |
|---|---|---|
np.loadtxt |
ValueError |
clean numeric or text columns |
np.genfromtxt |
nan (filling_values= to choose) |
numeric columns with gaps |
csv module + np.array |
your choice | mixed rows, custom parsing |
pd.read_csv(...).to_numpy() |
NaN |
real tables (module 24) |
Indexing and slicing
Section titled “Indexing and slicing”print(sales[0, 3], sales[-1, -1]) # one element: [row, column]print(sales[1], sales[:, 0]) # a row; a column (1-D)print(sales[:2, 2:]) # a block (2-D)print(sales[:, ::2]) # every second columnprint(sales[:, [0]].shape) # keep the axis: list index -> (3, 1)82368 38865[21926 27811 33103 58803] [40722 21926 16664][[52453 82368] [33103 58803]][[40722 52453] [21926 33103] [16664 24725]](3, 1)| Expression | Shape from (3, 4) |
View? |
|---|---|---|
a[0] |
(4,) |
yes |
a[:, 0] |
(3,) |
yes |
a[:, 0:1] |
(3, 1) |
yes |
a[1:, ::2] |
(2, 2) |
yes |
a[[0, 2]] |
(2, 4) |
no, copy |
a[a > 0] |
(n,) |
no, copy |
a[..., 0] |
(3,) |
yes; ... = all earlier axes |
Views and copies
Section titled “Views and copies”col = sales[:, 3] # viewpicked = sales[[0, 1]] # copyprint(np.shares_memory(col, sales), np.shares_memory(picked, sales), col.base is sales)safe = sales[:, 3].copy() # independentTrue False True| View (shares memory) | Copy (own memory) |
|---|---|
basic slices a[1:3], a[:, 0] |
masks a[m], fancy a[[0, 2]] |
reshape (usually), .T, ravel() (contiguous) |
.copy(), flatten(), astype() |
arithmetic results a + 1 |
Boolean masks
Section titled “Boolean masks”hot = temps > 22print(hot, hot.sum(), hot.mean()) # NaN > 22 is Falseprint(temps[hot])print(temps[(temps > 21) & (temps < 30)], temps[~np.isnan(temps)])print(np.any(temps > 30), np.all(temps > 20), np.count_nonzero(hot))fixed = temps.copy()fixed[fixed > 30] = np.nan # assign through a maskprint(fixed)[False True False True True] 3 0.6[22.3 24.52 38.03][22.3 24.52] [20.21 22.3 24.52 38.03]True False 3[20.21 22.3 nan 24.52 nan]| Want | Write | Not |
|---|---|---|
| and / or / not | (a > 1) & (b < 2), |, ~m |
and, or, not (ValueError) |
| membership | np.isin(ids, ["S3", "S4"]) |
ids in [...] |
positions of True |
np.nonzero(m), np.where(m), np.argwhere(m) |
|
first True |
np.argmax(m) (check m.any() first) |
Fancy indexing and sorting
Section titled “Fancy indexing and sorting”names = np.array(["S01", "S02", "S03"])total = sales.sum(axis=1)top = np.argsort(total)[::-1] # largest firstprint(names[top], total[top])print(sales[[0, 1], [3, 0]]) # pairs (0, 3), (1, 0) -> 2 valuesprint(sales[np.ix_([0, 1], [3, 0])]) # 2 x 2 blockprice = np.array([79.99, 249.0, 1299.0])print(price[[0, 2, 2, 1]]) # lookup table: codes -> valuesprint(np.sort(total), np.searchsorted([300_000, 600_000], [250_000, 650_000]))['S01' 'S02' 'S03'] [220900 141643 115188][82368 21926][[82368 40722] [58803 21926]][ 79.99 1299. 1299. 249. ][115188 141643 220900] [0 2]np.argpartition(x, -k)[-k:]: the topkpositions without a full sort (unordered).np.unique(x, return_index=True, return_inverse=True, return_counts=True): labels, first positions, positions of every element, counts.np.add.at(m, (rows, cols), values)accumulates repeated positions.m[rows, cols] += valuesdoes not.
Broadcasting
Section titled “Broadcasting”Rule: align shapes on the right; each axis pair must be equal or contain a 1; a missing axis counts as 1.
| A | B | Result |
|---|---|---|
(3, 4) |
() |
(3, 4) |
(3, 4) |
(4,) |
(3, 4) |
(3, 4) |
(3, 1) |
(3, 4) |
(3, 1) |
(1, 4) |
(3, 4) (outer) |
(14, 144, 4) |
(1, 144, 4) |
(14, 144, 4) |
(3, 4) |
(3,) |
error |
share = sales / sales.sum(axis=1, keepdims=True) # (3, 4) / (3, 1)print(share.round(2))z = (sales - sales.mean(axis=0)) / sales.std(axis=0) # column z-scoresprint(z.mean(axis=0).round(6) + 0.0, z.std(axis=0))print(price[:, np.newaxis] * (1 - np.array([0, 0.1, 0.2]))) # outer table (3, 3)[[0.18 0.21 0.24 0.37] [0.15 0.2 0.23 0.42] [0.14 0.3 0.21 0.34]][0. 0. 0. 0.] [1. 1. 1. 1.][[ 79.99 71.991 63.992] [ 249. 224.1 199.2 ] [1299. 1169.1 1039.2 ]]Universal functions
Section titled “Universal functions”| Kind | Functions |
|---|---|
| arithmetic | + - * / // % **, np.add, np.multiply, np.power |
| math | np.sqrt, np.exp, np.log, np.log1p, np.abs, np.sign |
| rounding | np.round(a, 2), np.floor, np.ceil, np.trunc |
| comparison | > >= == !=, np.maximum(a, b), np.minimum(a, b) |
| floats | np.isnan, np.isfinite, np.isclose |
| differences | np.diff(a) (length − 1), np.cumsum, np.gradient |
np.maximum(a, b) is element-wise between two arrays; np.max(a) reduces one array.
Aggregations and axis
Section titled “Aggregations and axis”print(sales.sum(), sales.sum(axis=0), sales.sum(axis=1))print(sales.mean(axis=1), sales.max(axis=0), sales.argmax(axis=1))print(sales.cumsum(axis=1)[0], np.percentile(sales, [25, 50, 75]))print(f"{sales.std():.1f} {sales.std(ddof=1):.1f}") # population (ddof=0), sample477731 [ 79312 108102 110281 180036] [220900 141643 115188][55225. 35410.75 28797. ] [40722 45357 52453 82368] [3 3 3][ 40722 86079 138532 220900] [27039.5 36899.5 47131. ]17464.5 18241.1| Call | Shape from (14, 144, 4) |
|---|---|
a.sum() |
scalar |
a.sum(axis=0) |
(144, 4) |
a.sum(axis=(0, 1)) |
(4,) |
a.sum(axis=1, keepdims=True) |
(14, 1, 4) |
The named axis disappears. axis=0 → one result per column; axis=1 → one per row.
Missing values
Section titled “Missing values”print(temps.mean(), np.nanmean(temps), np.nanmedian(temps), np.nanmax(temps))print(np.isnan(temps).sum(), np.nan == np.nan)print(np.where(np.isnan(temps), np.nanmedian(temps), temps)) # fill gapsprint(np.nan_to_num(temps, nan=0.0))nan 26.265 23.41 38.031 False[20.21 22.3 23.41 24.52 38.03][20.21 22.3 0. 24.52 38.03]NaN-aware versions: nansum, nanmean, nanmedian, nanstd, nanvar, nanmin, nanmax, nanargmin, nanargmax, nanpercentile, nancumsum. An integer array cannot hold NaN.
Reshape, stack and split
Section titled “Reshape, stack and split”flat = np.arange(24)grid = flat.reshape(4, 6)print(grid.shape, flat.reshape(2, 3, -1).shape, grid.T.shape)print(np.concatenate([sales, sales]).shape) # axis=0 by defaultprint(np.concatenate([sales, sales], axis=1).shape)print(np.stack([sales, sales]).shape, np.column_stack([price, price]).shape)print([p.shape for p in np.split(sales, 2, axis=1)])print([len(p) for p in np.array_split(flat, 5)])print(sales[:, :, np.newaxis].shape, np.expand_dims(price, 0).shape)print(np.squeeze(sales[:, :1]).shape)(4, 6) (2, 3, 4) (6, 4)(6, 4)(3, 8)(2, 3, 4) (3, 2)[(3, 2), (3, 2)][5, 5, 5, 5, 4](3, 4, 1) (1, 3)(3,)| Function | Does |
|---|---|
a.reshape(r, -1) |
new shape, same elements (row order) |
a.ravel() / a.flatten() |
to 1-D: view if possible / always a copy |
a.T, np.transpose(a, axes) |
swap or reorder axes |
np.concatenate(list, axis) |
join along an existing axis |
np.stack(list, axis) |
join along a new axis |
np.vstack, np.hstack, np.column_stack |
rows, columns, 1-D as columns |
np.split(a, n) / np.array_split(a, n) |
equal parts / nearly equal parts |
a[:, np.newaxis], np.expand_dims, np.squeeze |
add or drop length-1 axes |
Conditional logic
Section titled “Conditional logic”v = np.array([2.1, 5.0, 12.3, np.nan])t = np.array([22.0, 34.0, 25.0, 43.0])status = np.select([(v >= 11.2) | (t >= 42), (v >= 4.5) | (t >= 33)], ["fail", "warn"], default="ok")print(status)print(np.where(t > 30, "hot", "ok"), np.where(t > 30)[0])print(np.clip(t, 20, 35), np.digitize(t, [25, 35]))['ok' 'warn' 'fail' 'fail']['ok' 'hot' 'ok' 'hot'] [1 3][22. 34. 25. 35.] [0 1 1 2]np.where(cond, a, b): element-wise if/else.np.where(cond): positions.np.select: first true condition wins; NaN comparisons areFalse.np.digitize(x, edges): bin number of each value.
Linear algebra
Section titled “Linear algebra”units = np.array([[101, 63, 31], [56, 34, 17], [42, 29, 11]])revenue = units @ price # (3, 3) @ (3,) -> (3,)print(revenue, np.linalg.solve(units, revenue))print(np.allclose(np.linalg.inv(units) @ units, np.eye(3)))print(round(float(np.linalg.det(units)), 1))x = np.array([1200.0, 1600.0, 2000.0, 2400.0])y = np.array([260.0, 395.0, 520.0, 650.0])X = np.column_stack([np.ones_like(x), x]) # design matrixcoef, residual_ss, rank, sv = np.linalg.lstsq(X, y)print(coef, rank, np.allclose(np.linalg.solve(X.T @ X, X.T @ y), coef)) # normal eqsw, vecs = np.linalg.eigh(np.array([[2.0, 1.0], [1.0, 2.0]]))print(w, np.linalg.norm([3.0, 4.0]))U, s, Vt = np.linalg.svd(sales, full_matrices=False)print(s, (s**2 / np.sum(s**2)).round(3))print(np.allclose(U * s @ Vt, sales)) # U diag(s) Vt rebuilds M[64034.99 35028.44 24869.58] [ 79.99 249. 1299. ]True231.0[-126.5 0.324] 2 True[1. 3.] 5.0[149970.083 12497.475 5640.947] [0.992 0.007 0.001]True| Task | Function | Note |
|---|---|---|
| matrix product, dot product | A @ B, a @ b |
* is element-wise |
| outer product | np.outer(u, v) |
u[:, None] * v |
| square system | np.linalg.solve |
LinAlgError if singular |
| least squares | np.linalg.lstsq(X, y) |
y may be (n, k): k fits at once |
| inverse, determinant | np.linalg.inv, np.linalg.det |
rarely needed |
| symmetric eigen | np.linalg.eigh |
real, ascending |
| general eigen | np.linalg.eig |
dtype depends on the version (complex on 2.5) |
| SVD | np.linalg.svd(M, full_matrices=False) |
s descending; signs arbitrary |
| norms, condition | np.linalg.norm, np.linalg.cond |
large cond: unstable solve |
| correlation, covariance | np.corrcoef(X, rowvar=False), np.cov(X, rowvar=False) |
columns as variables |
Random numbers
Section titled “Random numbers”rng = np.random.default_rng(42)print(rng.normal(22.0, 0.5, size=3), rng.integers(1, 6, size=4))print(rng.choice(["S1", "S2", "S3"], size=4), rng.choice(10, size=3, replace=False))print(rng.permutation(5), rng.poisson(20.4, size=3), rng.uniform(0, 1, 2))a, b = np.random.default_rng(1).random(3), np.random.default_rng(1).random(3)print(np.array_equal(a, b)) # same seed, same numbers[22.152 21.48 22.375] [1 4 2 1]['S2' 'S3' 'S3' 'S3'] [9 7 5][3 0 2 4 1] [25 16 12] [0.632 0.758]True| Need | Call |
|---|---|
| normal noise | rng.normal(loc, scale, size) |
integers in [low, high) |
rng.integers(low, high, size) |
floats in [0, 1) |
rng.random(size) |
| sample, weighted sample | rng.choice(a, size, replace=..., p=...) |
| shuffle | rng.permutation(a) (copy), rng.shuffle(a) (in place) |
| counts per interval | rng.poisson(lam, size) |
| bootstrap positions | rng.integers(0, n, size=(rounds, n)) |
| independent streams | rng.spawn(4) |
| Slow | Fast |
|---|---|
[x * 2 for x in a] |
a * 2 |
for loop with if |
mask or np.where |
sum(a) (Python built-in) |
a.sum() |
growing with np.append in a loop |
collect in a list, then np.array(list) once, or preallocate with np.empty(n) |
| dict lookups per row | lookup array + fancy indexing |
np.vectorize(f) |
real array expressions (np.vectorize is a loop) |
Measure with timeit (module 15). Typical speed-ups of vectorized code over Python loops are 10× to 100×.
Gotchas
Section titled “Gotchas”and,or,noton arrays raiseValueError: The truth value of an array ... is ambiguous. Use&,|,~.a > 1 & bmeansa > (1 & b). Always put comparisons in parentheses.- A slice is a view: changing it changes the original.
.copy()when you edit a part. x == np.nanis alwaysFalse. Usenp.isnan(x).- One NaN makes
sum,meanandmaxNaN. Use thenanfunctions. - Small integer arrays wrap around silently:
np.array([100], np.int8) * 2is[-56]. NumPy scalars (np.int8(100) + np.int8(100)) also give-56, but with aRuntimeWarning. astype(int)truncates toward zero. Round first.np.stdusesddof=0; pandas.std()usesddof=1.(n, m) / (n,)fails. Usekeepdims=Trueor[:, np.newaxis].a[[0, 1], [2, 3]]picks 2 elements, not a block. Usenp.ix_.a[idx] += 1with repeatedidxadds once per position. Usenp.add.atornp.bincount.reshapetrusts the element order. Check the order of the rows first.np.linalg.eigreturns complex arrays on NumPy 2.5 (earlier 2.x releases cast to real). Do not rely on the dtype: useeighfor symmetric matrices, or.realafternp.allclose(w.imag, 0).- SVD and eigenvector signs are arbitrary. Do not interpret a sign on its own.
repr(), the REPL and containers shownp.float64(3.0). Useprint,float()or.tolist().np.random.seed()andnp.random.rand()are the legacy global API. Usenp.random.default_rng(seed).- NumPy 2 removed old aliases:
np.NaN,np.Inf,np.float_,np.product,np.alltrue,np.round_,np.trapz,np.in1d,np.row_stack,a.ptp()raiseAttributeError. Usenp.nan,np.inf,np.float64,np.prod,np.all,np.round,np.trapezoid,np.isin,np.vstack,np.ptp(a). - An
objector<Uarray is not fast. NumPy is for numbers; use pandas or Polars for text-heavy tables.