Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python numpy generate an array of random binary values according to probabilities

Is there any way in which I can do the following in a single line? Suppose I have an array of probabilities,

p=np.array([0.75, 0.63, 0.33, 0.25, 0.47])

where each value corresponds to the probability of selecting a 1 and (1-p) corresponds to probability of selecting 0, i.e., 0.75 is the probability of selecting 1, and 1 - 0.75 is probability of selecting 0, 0.63 for selecting 1, and 1 - 0.63 for selecting 0 and so on. Is there any easier way for me to do the following, hopefully without a loop?

values = np.empty(p.shape)
for i, prob in enumerate(p):
    values[i] = np.random.binomial(1, prob)

I know it can be done using map but is there a way to directly do it in numpy?

like image 359
Aditya369 Avatar asked Sep 11 '25 16:09

Aditya369


1 Answers

values = np.random.binomial(1, p)
like image 93
vahndi Avatar answered Sep 13 '25 05:09

vahndi