Search code examples
pythonarraysnumpyrandomprobability

Generate list of numbers from a list with probability weights


How would one go about generating a list of random numbers from a list of 35 numbers with given probabilities:

Probability of number in range (1,5) - p1 = 0.5

Probability of number in range (6,15) - p2 = 0.25

Probability of number in range (16,35) - p3 = 0.25

I tried using numpy.random.choice() but I have no idea how to jam in possible lists of numbers.


Solution

  • If you want to select uniformly from each group:

    p=np.array([0.5/5]*5+[0.25/30]*30)
    np.random.choice(np.arange(1,36),p=p/p.sum())
    

    UPDATE:

    and if you would like to select a list of random numbers (you can also set with or without replacement flag):

    np.random.choice(np.arange(1,36), size=N, replace=True, p=p/p.sum())