NumPy Random Numbers

Lesson 14 of 17

NumPy can generate random numbers for simulations, sampling and test data. The modern way is to create a random generator with np.random.default_rng().

Create a generator

Example

Python
import numpy as np

rng = np.random.default_rng(42)
print(rng.integers(1, 100))

Output

Plain Text
9

The number 42 is a seed. With the same seed you get the same numbers on every run, which makes results reproducible. Leave it out to get different numbers each time. The examples here use a seed so your output matches.

Random integers

Example

Python
import numpy as np

rng = np.random.default_rng(42)
print(rng.integers(1, 7, size=10))

Output

Plain Text
[1 5 4 3 3 6 1 5 2 1]

This simulates 10 dice rolls. The high value 7 is excluded, so you get numbers from 1 to 6.

Random floats

Example

Python
import numpy as np

rng = np.random.default_rng(42)
print(rng.random(3))
print(rng.random((2, 2)))

Output

Plain Text
[0.77395605 0.43887844 0.85859792]
[[0.69736803 0.09417735]
 [0.97562235 0.7611397 ]]

random() returns floats between 0 (included) and 1 (excluded).

Pick from a list with choice()

Example

Python
import numpy as np

rng = np.random.default_rng(42)
colors = np.array(["red", "green", "blue"])

print(rng.choice(colors, size=5))
print(rng.choice(colors, size=5, p=[0.7, 0.2, 0.1]))

Output

Plain Text
['red' 'blue' 'green' 'green' 'green']
['red' 'red' 'blue' 'green' 'green']

The p argument sets the probability of each item, and the values must add up to 1.

Normal distribution

Example

Python
import numpy as np

rng = np.random.default_rng(42)
heights = rng.normal(loc=170, scale=10, size=5)
print(np.round(heights, 1))

Output

Plain Text
[173.  159.6 177.5 179.4 150.5]

loc is the mean and scale is the standard deviation.

Shuffle and permutation

Example

Python
import numpy as np

rng = np.random.default_rng(42)
arr = np.arange(1, 6)

print(rng.permutation(arr))
rng.shuffle(arr)
print(arr)

Output

Plain Text
[5 3 4 2 1]
[4 1 2 3 5]

permutation() returns a shuffled copy; shuffle() shuffles the array in place.

You will also see older code such as np.random.randint() and np.random.seed(). It still works, but new code should use default_rng().