4

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?

1 Answer 1

4
values = np.random.binomial(1, p)
Sign up to request clarification or add additional context in comments.

2 Comments

I never knew it could be used with an array of probabilities. I should have read the documentation better. I'm sorry. Thanks a lot.
No worries. Not your fault - the documentation in ipython specifies it should be a float but most operations in numpy are designed to be broadcastable so it's worth giving it a try even if the docs say something else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.