NumPy Random Module
Why random matters in analytics
Section titled “Why random matters in analytics”Random values help with:
- Simulation and Monte Carlo experiments
- Creating synthetic datasets for testing
- Sampling
- Bootstrapping
numpy.random supplements Python’s built-in random module with functions that generate whole arrays of samples at once. Python’s random module only produces one value at a time, so for large samples NumPy is dramatically faster.
Recommended API: default_rng()
Section titled “Recommended API: default_rng()”Modern NumPy recommends using a Generator object instead of the old global numpy.random functions:
import numpy as np
rng = np.random.default_rng(42)
print(rng.integers(1, 10, size=5))flowchart LR A["np.random.default_rng(seed)"] --> B["Generator object (rng)"] B --> C["rng.integers(...)"] B --> D["rng.normal(...)"] B --> E["rng.choice(...)"] B --> F["rng.shuffle(...)"] C --> G["Same seed -> same numbers every run"] D --> G E --> G
Seeding (reproducibility)
Section titled “Seeding (reproducibility)”Seeding ensures you get the same results each run — essential for reproducible experiments and tutorials.
import numpy as np
rng = np.random.default_rng(123)
print(rng.normal(size=3))Random integers
Section titled “Random integers”import numpy as np
rng = np.random.default_rng(7)
arr = rng.integers(low=0, high=100, size=10)
print(arr)Random floats
Section titled “Random floats”import numpy as np
rng = np.random.default_rng(7)
arr = rng.random(5) # uniform in [0, 1)
print(arr)Normal distribution
Section titled “Normal distribution”import numpy as np
rng = np.random.default_rng(7)
arr = rng.normal(loc=0, scale=1, size=5)
print(arr)Choice (sampling)
Section titled “Choice (sampling)”import numpy as np
rng = np.random.default_rng(7)
categories = np.array(["A", "B", "C"])
print(rng.choice(categories, size=10, replace=True))Weighted sampling:
import numpy as np
rng = np.random.default_rng(7)
values = np.array(["low", "medium", "high"])
probs = [0.6, 0.3, 0.1]
print(rng.choice(values, size=10, p=probs))Shuffle
Section titled “Shuffle”import numpy as np
rng = np.random.default_rng(7)
arr = np.arange(10)
rng.shuffle(arr)
print(arr)Synthetic dataset example
Section titled “Synthetic dataset example”import numpy as np
rng = np.random.default_rng(0)
n = 100
age = rng.integers(18, 60, size=n)
income = rng.normal(loc=60000, scale=15000, size=n)
X = np.column_stack([age, income])
print(X.shape)Continue to: Linear Algebra with NumPy to learn dot products, matrix multiplication, and solving systems.
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – A Seeded Generator
Section titled “Exercise 1 – A Seeded Generator”Exercise 2 – Weighted Sampling
Section titled “Exercise 2 – Weighted Sampling”Exercise 3 – Shuffle In Place
Section titled “Exercise 3 – Shuffle In Place”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading