Fastest way to simulate multiple given multiple probabilities in Python?

Viewed 103

I have a list of probabilities p = [p1, p2, …, pn].

All I want is to simulate a list s = [0, 1, 0, 0, 1, …, 1], whose first element is 0 with probability p1 and 1 with probability 1 - p1, and then so on for the next elements, always matching the corresponding probabilities in the p-list.

Currently my solution is to for-loop over p, and then append to s the output from np.random.choice() called on each individual pn.

s = []
for item in p:
    s.append(np.random.choice([0, 1], p=[item, 1 - item]))
1 Answers

You just need to draw your numbers and element-wise compare them with your p. just decide if for 1 you want > or >=

import numpy as np

p = np.array([0.2, 0.5, 0, 1.0, 0.9, 0.3, 0.1, 0.8])
x = np.random.random(size=p.shape)
ans = (x>p).astype('int')

print(p)
print(x)
print(ans)


[0.2 0.5 0.  1.  0.9 0.3 0.1 0.8]
[0.08990063 0.51804083 0.9049705  0.0885368  0.1273564  0.18583925
 0.51488052 0.23258143]
[0 1 1 0 0 0 1 0]
Related