All Cheat Sheets

NumPy Cheat Sheet

NumPy cheat sheet for Python: array creation, dtypes, reshape, indexing and boolean masks, broadcasting, axis aggregations, linear algebra, default_rng random numbers, and views vs copies.

Creating Arrays

Importimport numpy as np
From a lista = np.array([1, 2, 3]) m = np.array([[1, 2], [3, 4]])
Zeros / onesnp.zeros((3, 4)) np.ones((2, 2), dtype=np.int32)
Constant fillnp.full((2, 3), 7)
Uninitialisednp.empty((1000, 3))Contents are arbitrary; fill before reading
Rangenp.arange(0, 10, 2) # [0 2 4 6 8]Stop is exclusive
Evenly spacednp.linspace(0, 1, 5) # [0. .25 .5 .75 1.]Stop is inclusive; prefer over arange for floats
Identity matrixnp.eye(3)
Same shape asnp.zeros_like(a) np.ones_like(a, dtype=float)
No-copy conversionnp.asarray(data)Returns the input unchanged if it is already an ndarray

Data Types

Inspect dtypea.dtype # dtype('int64')
Set on creationnp.array([1, 2], dtype=np.float32)
Converta.astype(np.float64)Always returns a new array
Common dtypesbool, int8/16/32/64, uint8, float16/32/64, complex128, str_ (U), object
Type limitsnp.iinfo(np.int32).max np.finfo(np.float32).eps
Bytesa.itemsize # bytes per element a.nbytes # total bytes
Integer overflownp.array([127], dtype=np.int8) + 1 # [-128]Wraps silently; pick a wide enough dtype
NaN is floatnp.array([1, np.nan]).dtype # float64Integer arrays cannot hold NaN

Shape & Reshape

Shape / dims / sizea.shape # (3, 4) a.ndim # 2 a.size # 12
Reshapea.reshape(4, 3) a.reshape(2, -1)-1 lets NumPy infer that dimension
Flattena.ravel() # view when possible a.flatten() # always a copy
Transposea.T np.transpose(x, (1, 0, 2))
Add an axisv[:, np.newaxis] # (n,) -> (n, 1) np.expand_dims(v, 0) # (1, n)
Remove size-1 axesnp.squeeze(x)
Join along axisnp.concatenate([a, b], axis=0)
Stack (new axis)np.stack([a, b]) np.vstack([a, b]) np.hstack([a, b])
Splitnp.split(a, 3) np.array_split(a, 4)array_split allows unequal parts

Indexing & Slicing

Elementa[0] a[-1] m[1, 0]
Slicea[1:4] a[::2] a[::-1]start:stop:step, stop exclusive
Rows / columnsm[0] # first row m[:, 0] # first column m[1:, :2]
Fancy indexinga[[0, 2, 4]] m[[0, 1], [1, 0]] # elements (0,1) and (1,0)Returns a copy
Boolean maska[a > 0]Returns a copy
Combine masksa[(a > 0) & (a < 10)]Use & | ~ with parentheses, not and / or
Assign with maska[a < 0] = 0
Where (ternary)np.where(a > 0, a, 0)
Indices of matchesnp.nonzero(a > 5) np.argwhere(m > 5)
Ellipsisx[..., 0]All leading axes, last axis index 0

Broadcasting

Scalar with arraya * 2 + 1
Row vector to matrixm = np.ones((3, 4)) m + np.arange(4) # (3,4) + (4,)
Column vectorm + np.arange(3)[:, None] # (3,4) + (3,1)
Outer product shapenp.arange(3)[:, None] * np.arange(4) # -> (3, 4)
The ruleCompare shapes from the right; dimensions are compatible if equal or one of them is 1
Incompatiblenp.ones((3, 4)) + np.ones(3) # ValueError(3,4) vs (3,): last dims 4 and 3 differ; reshape to (3, 1)
Normalise columns(X - X.mean(axis=0)) / X.std(axis=0)

Math & Aggregations

Element-wise opsa + b a * b a ** 2 a / b
Universal functionsnp.sqrt(a) np.exp(a) np.log(a) np.abs(a)
Sum all / by axism.sum() m.sum(axis=0) # per column m.sum(axis=1) # per rowaxis=0 collapses rows, axis=1 collapses columns
Keep dimensionsm.sum(axis=1, keepdims=True) # (n, 1)Result broadcasts back against m
Mean / stdm.mean(axis=0) m.std(ddof=1)ddof=1 for sample standard deviation
Min / max / argmaxa.min() a.max() a.argmax()
Cumulativenp.cumsum(a) np.cumprod(a) np.diff(a)
Ignore NaNnp.nansum(a) np.nanmean(a)
Round & clipnp.round(a, 2) np.clip(a, 0, 1)
Uniquevals, counts = np.unique(a, return_counts=True)
Sortnp.sort(a) idx = np.argsort(a)
Percentilesnp.percentile(a, [25, 50, 75]) np.median(a)

Linear Algebra

Matrix multiplyA @ B np.matmul(A, B)* is element-wise, not matrix multiplication
Dot productnp.dot(u, v)
Solve Ax = bx = np.linalg.solve(A, b)More stable and faster than inv(A) @ b
Inverse / determinantnp.linalg.inv(A) np.linalg.det(A)
Eigen decompositionw, V = np.linalg.eig(A) w, V = np.linalg.eigh(S) # symmetric
SVDU, s, Vt = np.linalg.svd(A, full_matrices=False)
Normnp.linalg.norm(v) np.linalg.norm(A, 'fro')
Least squaresx, *_ = np.linalg.lstsq(A, b, rcond=None)
Outer productnp.outer(u, v)

Random Numbers

Create a generatorrng = np.random.default_rng(42)Recommended API; seed for reproducibility
Uniform floatsrng.random((2, 3)) # [0, 1)
Integersrng.integers(0, 10, size=5)High is exclusive by default
Normal distributionrng.normal(loc=0, scale=1, size=1000)
Uniform rangerng.uniform(5, 10, size=3)
Choicerng.choice(a, size=3, replace=False)
Shufflerng.shuffle(a) # in place b = rng.permutation(a) # copy
Legacy APInp.random.seed(0); np.random.rand(3)Global state; prefer default_rng in new code

Saving & Loading

Binary .npynp.save("a.npy", a) a = np.load("a.npy")
Several arraysnp.savez_compressed("data.npz", X=X, y=y) d = np.load("data.npz"); X = d["X"]
Text / CSV outnp.savetxt("a.csv", a, delimiter=",", fmt="%.3f")
Text / CSV innp.loadtxt("a.csv", delimiter=",") np.genfromtxt("a.csv", delimiter=",", skip_header=1)genfromtxt handles missing values
Pickle safetynp.load uses allow_pickle=False by default; only enable it for trusted files

Common Pitfalls

Slices are viewsb = a[1:3] b[0] = 99 # also changes aBasic slicing shares memory with the original
Make a copyb = a[1:3].copy()
Fancy / boolean = copyb = a[[1, 2]] b[0] = 99 # a unchanged
Check sharingnp.shares_memory(a, b)
Float equalitynp.isclose(0.1 + 0.2, 0.3) np.allclose(x, y)Never compare floats with ==
NaN comparisonsnp.isnan(a)a == np.nan is always False
1-D vs column vectorShape (n,) is not (n, 1); reshape explicitly before broadcasting or matrix ops
Truth value of an arrayif (a > 0).any(): ... if (a > 0).all(): ...if a > 0 raises ValueError for arrays with more than one element
NumPy 2.0 removalsAliases such as np.float_, np.NaN and np.Inf were removed; use np.float64, np.nan, np.inf

Keep the references coming

One email a week: new and trending developer tools, fresh comparisons, and what shipped. Unsubscribe in one click.