vendredi 22 janvier 2016

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?




Aucun commentaire:

Enregistrer un commentaire