If I have a collection of items in a list. I want to choose from that list according to another list of weights.
For example my collection is ['one', 'two', 'three']
and the weights are [0.2, 0.3, 0.5]
, the I would expect the method to give me 'three' in about half of all draws.
What is the easiest way to do so ?
Weighted random choices mean selecting random elements from a list or an array by the probability of that element. We can assign a probability to each element and according to that element(s) will be selected. By this, we can select one or more than one element from the list, And it can be achieved in two ways.
Since numpy version 1.7 you can use numpy.random.choice()
:
elements = ['one', 'two', 'three'] weights = [0.2, 0.3, 0.5] from numpy.random import choice print(choice(elements, p=weights))
Since Python 3.6, you can do weighted random choice (with replacement) using random.choices
.
random.choices(population, weights=None, *, cum_weights=None, k=1)
Example usage:
import random random.choices(['one', 'two', 'three'], [0.2, 0.3, 0.5], k=10) # ['three', 'two', 'three', 'three', 'three', # 'three', 'three', 'two', 'two', 'one']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With