Home » excel » python – Randomly picking Items with Given Probabilities

# python – Randomly picking Items with Given Probabilities

Questions:

Currently i’m working on a project where I need to code something in Python but stumbled upon some obstacles. I have an excel sheet with 692 items (stock keeping units) with their corresponding sales numbers. The items are in sequence from most sold till least sold. I calculated both the probability and cumulative probability for each item as can be seen in images 1 and 2 below:

excel sheet

excel sheet 2

Based on the cumulative probability and following formula: =INDEX(A\$2:A\$721;COUNTIF(H\$2:H\$721;”<=”&RAND())+1)

randomly 20 items are selected from the 692 items to generate an order picking list, which can be seen in the following image:

generated pick list

Basically i want to do the same in Python. Thus, select a number of items from a large list based on their probability.

I found the following code, but not sure how to use it:

``````    import random
def random_pick(some_list, probabilities):
x = random.uniform(0, 1)
cumulative_probability = 0.0
for item, item_probability in zip(some_list, probabilities):
cumulative_probability += item_probability
if x < cumulative_probability: break
return item
``````

It would be great if someone could give me some directions in how to achieve this. Thanks in advance!

Use random.choices and give it some probabilities:

``````from collections import Counter
from random import choices

data = [1,2,3,4]
prob = [1,1,8,1] # 3 about 8 times more likely to being choosen then 1,2 or 4

c = Counter(choices(data,prob,k=1000)) # generate 1000 and count

print(c)
``````

Output:

``````Counter({3: 717, 1: 101, 2: 92, 4: 90})  # 3 being taken far more often - about 8:1:1:1 if
# you close both eyes and squint really hard ;)
``````