How to use Random.choices() method In NumPy

The choices() method returns multiple random elements from the list with replacement. You can weigh the possibility of each result with the weights parameter or the cum_weights parameter.

Syntax : random.choices(sequence, weights=None, cum_weights=None, k=1)

Parameters :
1. sequence is a mandatory parameter that can be a list, tuple, or string.
2. weights is an optional parameter which is used to weigh the possibility for each value.
3. cum_weights is an optional parameter which is used to weigh the possibility for each value but in this the possibility is accumulated
4. k is an optional parameter that is used to define the length of the returned list.

Example 1:

Python3

import random
 
 
sampleList = [100, 200, 300, 400, 500]
 
randomList = random.choices(
  sampleList, weights=(10, 20, 30, 40, 50), k=5)
 
print(randomList)

                    

Output:

[200, 300, 300, 300, 400]

You can also use cum_weight parameter. It stands for cumulative weight. By default, the function calculates cumulative weights from standard weights. So to expedite the program, use cum_weight. Cumulative weight is calculated by the formula:

let the relative weight of 5 elements be [5,10,20,30,35]
then their cum_weight will be [5,15,35,65,100]

Example:

Python3

import random
 
sampleList = [100, 200, 300, 400, 500]
randomList = random.choices(
  sampleList, cum_weights=(5, 15, 35, 65, 100), k=5)
 
print(randomList)

                    

Output:

[500, 500, 400, 300, 400]

How to get weighted random choice in Python?

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.

  1. By random.choices()
  2. By numpy.random.choice()

Similar Reads

Using Random.choices() method

The choices() method returns multiple random elements from the list with replacement. You can weigh the possibility of each result with the weights parameter or the cum_weights parameter....

Using numpy.random.choice() method

...

Contact Us