Create
np.array([[1, 2], [3, 4]])
Array from nested lists
np.zeros((<r>, <c>))
Array of zeros
np.ones and np.full((r, c), v) work alike.
np.arange(<start>, <stop>, <step>)
Evenly spaced by step
Stop is excluded. Float steps can surprise: prefer linspace.
np.linspace(<a>, <b>, <n>)
n points, both ends included
np.zeros_like(<a>)
Zeros with the shape and dtype of a
np.array(<seq>, dtype=np.float32)
Choose the dtype
Shape and join
a.reshape(<r>, -1)
Reshape, -1 infers one length
Needs the same element count; usually returns a view.
a.ravel() / a.flatten()
Flatten (view if possible / copy)
np.concatenate([<a>, <b>], axis=0)
Join along an existing axis
np.vstack([<a>, <b>]) / np.hstack([<a>,
<b>])
Stack vertically / horizontally
Reductions
a.sum() / a.mean()
Total / average of everything
a.sum(axis=0)
Collapse rows: one value per column
axis=1 gives one value per row.
a.min() / a.max()
Smallest / largest
a.argmax() / a.argmin()
Index of largest / smallest (flat)
Add axis=0 for per-column positions.
a.std() / a.var()
Standard deviation / variance
ddof=1 gives the sample estimate.
np.any(<mask>) / np.all(<mask>)
Any / all True
np.nansum(a) / np.nanmean(a)
Reductions that skip NaN
Random
rng = np.random.default_rng(<seed>)
Create a seeded generator
Use this instead of the legacy np.random.seed.
rng.random((<r>, <c>))
Uniform floats in [0, 1)
rng.integers(<lo>, <hi>, size=<n>)
Random ints, hi excluded
rng.normal(<mu>, <sigma>, size=<n>)
Normal samples
rng.choice(<a>, size=<n>, replace=False)
Sample from an array
rng.shuffle(<a>)
Shuffle in place
Save and load
np.save("<file>.npy", <a>)
Write one array (binary)
np.load("<file>.npy")
Read it back
np.savez("<file>.npz",
<name>=<a>)
Several arrays in one file
np.savetxt("<file>.csv", <a>,
delimiter=",")
Write plain text
np.loadtxt("<file>.csv",
delimiter=",")
Read plain text numbers
skiprows=1 skips a header; use pandas for messy files.
Recipes
Normalise columns
X = rng.normal(size=(100, 3))Z = (X - X.mean(axis=0)) / X.std(axis=0)print(Z.mean(axis=0).round(6))
Pairwise distances by broadcasting
d = np.linalg.norm( p[:, None, :] - p[None, :, :], axis=-1) # (n, n)
Fit a line
x = np.linspace(0, 1, 50)y = 2 * x + rng.normal(0, .1, 50)A = np.c_[x, np.ones_like(x)]m, b = np.linalg.lstsq(A, y)[0]
Replace values without a loop
a[np.isnan(a)] = 0a = np.where(a > 100, 100, a)