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
Import
import numpy as npFrom a list
a = np.array([1, 2, 3])
m = np.array([[1, 2], [3, 4]])Zeros / ones
np.zeros((3, 4))
np.ones((2, 2), dtype=np.int32)Constant fill
np.full((2, 3), 7)Uninitialised
np.empty((1000, 3))Contents are arbitrary; fill before readingRange
np.arange(0, 10, 2) # [0 2 4 6 8]Stop is exclusiveEvenly spaced
np.linspace(0, 1, 5) # [0. .25 .5 .75 1.]Stop is inclusive; prefer over arange for floatsIdentity matrix
np.eye(3)Same shape as
np.zeros_like(a)
np.ones_like(a, dtype=float)No-copy conversion
np.asarray(data)Returns the input unchanged if it is already an ndarrayData Types
Inspect dtype
a.dtype # dtype('int64')Set on creation
np.array([1, 2], dtype=np.float32)Convert
a.astype(np.float64)Always returns a new arrayCommon dtypesbool, int8/16/32/64, uint8, float16/32/64, complex128, str_ (U), object
Type limits
np.iinfo(np.int32).max
np.finfo(np.float32).epsBytes
a.itemsize # bytes per element
a.nbytes # total bytesInteger overflow
np.array([127], dtype=np.int8) + 1 # [-128]Wraps silently; pick a wide enough dtypeNaN is float
np.array([1, np.nan]).dtype # float64Integer arrays cannot hold NaNShape & Reshape
Shape / dims / size
a.shape # (3, 4)
a.ndim # 2
a.size # 12Reshape
a.reshape(4, 3)
a.reshape(2, -1)-1 lets NumPy infer that dimensionFlatten
a.ravel() # view when possible
a.flatten() # always a copyTranspose
a.T
np.transpose(x, (1, 0, 2))Add an axis
v[:, np.newaxis] # (n,) -> (n, 1)
np.expand_dims(v, 0) # (1, n)Remove size-1 axes
np.squeeze(x)Join along axis
np.concatenate([a, b], axis=0)Stack (new axis)
np.stack([a, b])
np.vstack([a, b])
np.hstack([a, b])Split
np.split(a, 3)
np.array_split(a, 4)array_split allows unequal partsIndexing & Slicing
Element
a[0]
a[-1]
m[1, 0]Slice
a[1:4]
a[::2]
a[::-1]start:stop:step, stop exclusiveRows / columns
m[0] # first row
m[:, 0] # first column
m[1:, :2]Fancy indexing
a[[0, 2, 4]]
m[[0, 1], [1, 0]] # elements (0,1) and (1,0)Returns a copyBoolean mask
a[a > 0]Returns a copyCombine masks
a[(a > 0) & (a < 10)]Use & | ~ with parentheses, not and / orAssign with mask
a[a < 0] = 0Where (ternary)
np.where(a > 0, a, 0)Indices of matches
np.nonzero(a > 5)
np.argwhere(m > 5)Ellipsis
x[..., 0]All leading axes, last axis index 0Broadcasting
Scalar with array
a * 2 + 1Row vector to matrix
m = np.ones((3, 4))
m + np.arange(4) # (3,4) + (4,)Column vector
m + np.arange(3)[:, None] # (3,4) + (3,1)Outer product shape
np.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
Incompatible
np.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 ops
a + b
a * b
a ** 2
a / bUniversal functions
np.sqrt(a)
np.exp(a)
np.log(a)
np.abs(a)Sum all / by axis
m.sum()
m.sum(axis=0) # per column
m.sum(axis=1) # per rowaxis=0 collapses rows, axis=1 collapses columnsKeep dimensions
m.sum(axis=1, keepdims=True) # (n, 1)Result broadcasts back against mMean / std
m.mean(axis=0)
m.std(ddof=1)ddof=1 for sample standard deviationMin / max / argmax
a.min()
a.max()
a.argmax()Cumulative
np.cumsum(a)
np.cumprod(a)
np.diff(a)Ignore NaN
np.nansum(a)
np.nanmean(a)Round & clip
np.round(a, 2)
np.clip(a, 0, 1)Unique
vals, counts = np.unique(a, return_counts=True)Sort
np.sort(a)
idx = np.argsort(a)Percentiles
np.percentile(a, [25, 50, 75])
np.median(a)Linear Algebra
Matrix multiply
A @ B
np.matmul(A, B)* is element-wise, not matrix multiplicationDot product
np.dot(u, v)Solve Ax = b
x = np.linalg.solve(A, b)More stable and faster than inv(A) @ bInverse / determinant
np.linalg.inv(A)
np.linalg.det(A)Eigen decomposition
w, V = np.linalg.eig(A)
w, V = np.linalg.eigh(S) # symmetricSVD
U, s, Vt = np.linalg.svd(A, full_matrices=False)Norm
np.linalg.norm(v)
np.linalg.norm(A, 'fro')Least squares
x, *_ = np.linalg.lstsq(A, b, rcond=None)Outer product
np.outer(u, v)Random Numbers
Create a generator
rng = np.random.default_rng(42)Recommended API; seed for reproducibilityUniform floats
rng.random((2, 3)) # [0, 1)Integers
rng.integers(0, 10, size=5)High is exclusive by defaultNormal distribution
rng.normal(loc=0, scale=1, size=1000)Uniform range
rng.uniform(5, 10, size=3)Choice
rng.choice(a, size=3, replace=False)Shuffle
rng.shuffle(a) # in place
b = rng.permutation(a) # copyLegacy API
np.random.seed(0); np.random.rand(3)Global state; prefer default_rng in new codeSaving & Loading
Binary .npy
np.save("a.npy", a)
a = np.load("a.npy")Several arrays
np.savez_compressed("data.npz", X=X, y=y)
d = np.load("data.npz"); X = d["X"]Text / CSV out
np.savetxt("a.csv", a, delimiter=",", fmt="%.3f")Text / CSV in
np.loadtxt("a.csv", delimiter=",")
np.genfromtxt("a.csv", delimiter=",", skip_header=1)genfromtxt handles missing valuesPickle safetynp.load uses allow_pickle=False by default; only enable it for trusted files
Common Pitfalls
Slices are views
b = a[1:3]
b[0] = 99 # also changes aBasic slicing shares memory with the originalMake a copy
b = a[1:3].copy()Fancy / boolean = copy
b = a[[1, 2]]
b[0] = 99 # a unchangedCheck sharing
np.shares_memory(a, b)Float equality
np.isclose(0.1 + 0.2, 0.3)
np.allclose(x, y)Never compare floats with ==NaN comparisons
np.isnan(a)a == np.nan is always False1-D vs column vectorShape (n,) is not (n, 1); reshape explicitly before broadcasting or matrix ops
Truth value of an array
if (a > 0).any(): ...
if (a > 0).all(): ...if a > 0 raises ValueError for arrays with more than one elementNumPy 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.

