Source From Here
QuestionHave you ever wondered how to select random elements from a list with different probability in Python? In this article, we will discuss how to do the same. Let’s first consider the below example.
- import random
- sam_Lst = [10, 20, 3, 4, 100]
- ran = random.choice(sam_Lst)
- print(ran)
HowTo
The function which will help us in this situation is random.choices(). This function allows making weighted random choices in python with replacement:
- random.choices(population, weights=None, *, cum_weights=None, k=1)
Case 1: Using Relative weights
The weight assigned to an element is known as relative weight.
Example1:
- import random
- # Creating a number list
- num_lst = [1, 22, 43, 19, 13, 29]
- print(random.choices(num_lst, weights=(14, 25, 30, 45, 55, 10), k=6))
In the above example, we assign weights to every element of the list. The weight of the element ‘13′ is highest i.e 55, so the probability of its occurrence is maximum. As we can see in the output, element 13 occurs 3 times, 19 occurs 2 times, and so on. So, now the probability of choosing an element from the list is different.
Example 2:
- import random
- # Creating a name list
- name_lst = ['October', 'November', 'December', 'January', 'March', 'June']
- print(random.choices(name_lst, weights=(40, 25, 30, 5, 15, 80), k=3))
In the above example, the weight of element ‘June’ is maximum so its probability of selection will be maximum. And here, k=3 which means we are choosing only the top 3 elements from the list.
Case 2: Using Cumulative weights
The cumulative weight of an element is determined by adding the weight of its previous element and its own weight.
Example 1:
- import random
- # Creating a number list
- num_lst = [1, 22, 93, 19, 13, 25]
- print(random.choices(num_lst, cum_weights=(7, 13, 15, 20, 25, 20), k=6))
In the above example, the cumulative weight of element ‘19′ is maximum, so the probability of its selection will also be maximum.
沒有留言:
張貼留言