np.random
NumPy’s modern random API is np.random.default_rng(). It returns a Generator with explicit, named distributions — faster, more reproducible, and better-defaulted than the legacy module-level functions.
default_rng patterns
EXAMPLE
import numpy as np
# 1) Create — pass a seed for reproducibility
rng = np.random.default_rng(seed=42)
# 2) Sample distributions
rng.integers(0, 100, size=5) # uniform int [0, 100)
rng.random(size=(3, 4)) # uniform float [0, 1)
rng.normal(loc=0, scale=1, size=(2, 3)) # normal
rng.standard_normal(size=10) # N(0, 1) shortcut
rng.binomial(n=10, p=0.3, size=100)
rng.poisson(lam=4.0, size=1000)
rng.exponential(scale=1.0, size=100)
# 3) Choice — sample with / without replacement
rng.choice(['red', 'green', 'blue'], size=10)
rng.choice(10, size=3, replace=False) # 3 distinct picks 0..9
rng.choice(10, size=5, p=[0.5, 0.1, 0.1, 0.05, 0.05, 0.05, 0.05, 0.05, 0.025, 0.025])
# 4) Shuffle / permutation
arr = np.arange(10)
rng.shuffle(arr) # in place
rng.permutation(10) # NEW array
rng.permutation(arr)
# 5) Reproducibility — seeding
rng1 = np.random.default_rng(0)
rng2 = np.random.default_rng(0)
assert (rng1.random(5) == rng2.random(5)).all() # identical
# 6) Splitting — independent streams for parallel work
from numpy.random import SeedSequence
seeds = SeedSequence(42).spawn(4)
rngs = [np.random.default_rng(s) for s in seeds] # 4 independent generators
# 7) Pandas — sample rows
import pandas as pd
df = pd.DataFrame({'x': range(100)})
df.sample(n=10, random_state=42)
df.sample(frac=0.1, random_state=42)
# 8) Train/test split — sklearn (which uses RandomState under the hood)
from sklearn.model_selection import train_test_split
Xtr, Xte = train_test_split(df, test_size=0.2, random_state=42)
# 9) Legacy API — avoid in new code
np.random.seed(42)
np.random.rand(3) # global state; tests / parallel code → bugs
Why it matters
Avoid np.random.* module functions in new code — they share global state. Pass an explicit rng through your code; reproducibility and parallelism stop being painful.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
import numpy as np rng = np.random.default_rng(seed=42) print(rng.integers(0, 10, size=5)) print(rng.normal(loc=0, scale=1, size=(2, 3)))Try it Yourself »
Discussion
Loading…