How to get weighted random choice in Python?
Published on Aug. 22, 2023, 12:15 p.m.
To get a weighted random choice in Python, you can use the random.choices
method from the built-in random
module. This method takes a sequence of choices and a corresponding sequence of weights, and returns a random choice based on the given weights. Here’s an example:
import random
choices = ['A', 'B', 'C']
weights = [0.1, 0.3, 0.6]
result = random.choices(choices, weights)
print(result)
In this example, we define choices
list with the possible values and weights
list with corresponding weights. We then call random.choices()
method with these two lists to get a random weighted choice. The probability of getting each choice is proportional to its assigned weight.
Note that the sum of the weights should be equal to 1, else we normalize the weights to sum up to 1.
using NumPy
To get a weighted random choice in Python using NumPy, you can use the numpy.random.choice
method which allows you to specify the choices and weights as input parameters. Here’s an example:
import numpy as np
choices = ['A', 'B', 'C']
weights = [0.1, 0.3, 0.6]
result = np.random.choice(choices, 1, p=weights)
print(result)
In this example, we import the NumPy library and create choices
list containing possible values and weights
list containing the corresponding weights.
We then call the numpy.random.choice()
function with the choices
and weights
lists as input parameters, followed by the number of samples we want to generate as the second parameter (in this case, 1) and the probability weights using the p
parameter. The p
parameter should be a 1-D array-like object containing the weights associated with each element in choices
.
The function returns a list of randomly chosen items based on the probability weights.