NumPy Cheatsheet
Random
Use this NumPy reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Modern API (NumPy ≥ 1.17 — preferred)
Use numpy.random.default_rng() instead of the legacy np.random.* module-level functions. It is faster, reproducible, and supports multiple independent generators.
import numpy as np rng = np.random.default_rng() # new Generator with random seed rng = np.random.default_rng(42) # fixed seed → reproducible rng = np.random.default_rng(seed=np.random.SeedSequence()) # Underlying BitGenerator (PCG64 by default) rng = np.random.Generator(np.random.PCG64(42)) rng = np.random.Generator(np.random.Philox(42)) # parallel-safe rng = np.random.Generator(np.random.SFC64(42)) # fastest rng = np.random.Generator(np.random.MT19937(42)) # Mersenne Twister (legacy compat)
Integers
rng.integers(10) # scalar in [0, 10) rng.integers(0, 10) # [low, high) — high is exclusive rng.integers(0, 10, size=5) # array of 5 rng.integers(0, 10, size=(3, 4)) # 3×4 array rng.integers(0, 10, dtype=np.int32) rng.integers(0, 10, endpoint=True) # [low, high] inclusive
Floats in [0, 1)
rng.random() # scalar in [0.0, 1.0) rng.random(size=5) # (5,) array rng.random(size=(3, 4)) # (3, 4) array rng.random(dtype=np.float32) # float32 output
Uniform Distribution
rng.uniform() # [0.0, 1.0) — same as rng.random() rng.uniform(low=2.0, high=5.0) # scalar in [2, 5) rng.uniform(2.0, 5.0, size=(3, 4)) # (3, 4) array
Normal (Gaussian) Distribution
rng.standard_normal() # N(0, 1) scalar rng.standard_normal(size=(3, 4)) # (3, 4) array rng.normal(loc=0.0, scale=1.0) # N(μ, σ) rng.normal(mu, sigma, size=(100,))
Other Continuous Distributions
| Method | Description |
|---|---|
rng.exponential(scale) | Exponential with mean = scale |
rng.gamma(shape, scale) | Gamma distribution |
rng.beta(a, b) | Beta distribution |
rng.chisquare(df) | Chi-square |
rng.f(dfnum, dfden) | F-distribution |
rng.standard_t(df) | Student's t |
rng.laplace(loc, scale) | Laplace (double exponential) |
rng.logistic(loc, scale) | Logistic |
rng.lognormal(mean, sigma) | Log-normal |
rng.power(a) | Power distribution |
rng.rayleigh(scale) | Rayleigh |
rng.weibull(a) | Weibull |
rng.vonmises(mu, kappa) | Von Mises (circular) |
rng.triangular(left, mode, right) | Triangular |
rng.pareto(a) | Pareto |
rng.gumbel(loc, scale) | Gumbel (extreme value) |
rng.wald(mean, scale) | Inverse Gaussian |
rng.exponential(scale=2.0, size=100) rng.gamma(shape=2.0, scale=1.0, size=(50,)) rng.lognormal(mean=0.0, sigma=1.0, size=200)
Discrete Distributions
rng.binomial(n=10, p=0.5) # number of successes rng.binomial(10, 0.5, size=1000) rng.poisson(lam=3.0) # Poisson count rng.poisson(3.0, size=(5, 5)) rng.geometric(p=0.3) # trials until first success rng.hypergeometric(ngood=10, nbad=5, nsample=7) rng.negative_binomial(n=5, p=0.3) rng.multinomial(n=100, pvals=[0.2, 0.3, 0.5]) # (3,) counts summing to 100 rng.multinomial(100, [0.2, 0.3, 0.5], size=10) # (10, 3) batch
Permutations and Sampling
a = np.arange(10) # Permutation — returns NEW array rng.permutation(10) # random permutation of np.arange(10) rng.permutation(a) # random permutation of a (copy) rng.permutation(a, axis=0) # permute along axis 0 # Shuffle — in-place rng.shuffle(a) # shuffles a in-place (no return value) rng.shuffle(b, axis=0) # shuffle along axis 0 (rows) # Choice — sampling with/without replacement rng.choice(10, size=5) # sample 5 from [0, 10) rng.choice(a, size=5, replace=False) # without replacement rng.choice(a, size=5, replace=True) # with replacement (default) rng.choice(a, size=5, p=[0.1]*10) # weighted sampling rng.choice(["a","b","c"], size=4) # works on any 1-D array
Multivariate Distributions
mean = [0, 0] cov = [[1, 0.5], [0.5, 1]] rng.multivariate_normal(mean, cov) # single sample, shape (2,) rng.multivariate_normal(mean, cov, size=100) # (100, 2) rng.multivariate_normal(mean, cov, check_valid="raise") # validate cov # Dirichlet rng.dirichlet(alpha=[1, 2, 3]) # (3,) array summing to 1 rng.dirichlet([1, 2, 3], size=50) # (50, 3) # Multinomial (discrete analog) rng.multinomial(n=20, pvals=[0.3, 0.5, 0.2])
Reproducibility and Seeding
# Reproducible rng = np.random.default_rng(42) a = rng.random(10) # always the same # Save / restore state (Generator uses BitGenerator state) state = rng.bit_generator.state rng.bit_generator.state = state # restore # Spawn independent child generators (for parallel work) children = rng.spawn(4) # list of 4 independent Generators # SeedSequence for parallel reproducibility ss = np.random.SeedSequence(42) child_seeds = ss.spawn(4) generators = [np.random.default_rng(s) for s in child_seeds]
Legacy API (module-level functions)
These are frozen legacy API — not deprecated, but no new features; NumPy recommends the Generator API above for new code. They share one global
RandomStateinstance and are not thread-safe.
| Legacy | Modern equivalent |
|---|---|
np.random.seed(42) | rng = np.random.default_rng(42) |
np.random.rand(3, 4) | rng.random((3, 4)) |
np.random.randn(3, 4) | rng.standard_normal((3, 4)) |
np.random.randint(0, 10, 5) | rng.integers(0, 10, 5) |
np.random.uniform(0, 1, 10) | rng.uniform(0, 1, 10) |
np.random.normal(0, 1, 10) | rng.normal(0, 1, 10) |
np.random.choice(a, 5) | rng.choice(a, 5) |
np.random.shuffle(a) | rng.shuffle(a) |
np.random.permutation(a) | rng.permutation(a) |
np.random.get_state() | rng.bit_generator.state |
np.random.set_state(s) | rng.bit_generator.state = s |
# Legacy (still works, not recommended for new code) np.random.seed(0) np.random.rand(3, 4) # uniform [0, 1) np.random.randn(3, 4) # standard normal np.random.randint(0, 100, size=10)
Common Patterns
# Random train/test split indices n = 1000 idx = rng.permutation(n) train_idx, test_idx = idx[:800], idx[800:] # Reproducible random weights for a neural net layer rng = np.random.default_rng(0) W = rng.normal(0, 0.01, size=(784, 256)) # Bootstrap sample data = np.random.randn(100) bootstrap = rng.choice(data, size=100, replace=True) # Random unit vectors v = rng.standard_normal(3) v /= np.linalg.norm(v)