How to get a weighted random selection with and without replacement with Python?

Sometimes, we want to get a weighted random selection with and without replacement with Python.

In this article, we’ll look at how to get a weighted random selection with and without replacement with Python.

How to get a weighted random selection with and without replacement with Python?

To get a weighted random selection with and without replacement with Python, we can use NumPy’s random module.

For instance, we write:

import numpy.random as rnd

sampling_size = 3
domain = ['white', 'blue', 'black', 'yellow', 'green']
probs = [.1, .2, .4, .1, .2]
sample = rnd.choice(domain, size=sampling_size, replace=False, p=probs)
print(sample)

We have a list of choices to choose from from the domain list.

probs has the probability of each value being chosen.

Next, we call rnd.choice with the domain, size, replace and p.

size is the number of choices to make.

replace set to False means the chosen item won’t be a choice again.

And p is the probabilities of each item being chosen.

Therefore, sample is something like ['green' 'blue' 'yellow'].

Conclusion

To get a weighted random selection with and without replacement with Python, we can use NumPy’s random module.