1

I have an ndarray where the elements sum to 1. My problem is quite simple, I want to randomly sample indices of this array where the probability of getting each index is the value of the corresponding element. Now, I want to do this many times and in large arrays with many dimensions so I was hoping to use np.random.choice or something similar rather than a for-loop but I can't seem to figure it out.

For example, if I have the ndarray

import numpy as np
a = np.array([[0.0, 0.2], [0.6, 0.2]])

I want to never get index (0,0) get (0,1) and (1,1) at a rate of 20 % each and get (1,0) at a rate of 60 %.

Is there a good and fast way of doing this that you know of? Many thanks!

1 Answer 1

1

You can flatten the array (from 2D to 1D) and use np.random.choice. Then you need to project the 1D index back to 2D using np.unravel_index:

np.unravel_index(np.random.choice(a.size, p = a.flatten()), a.shape)
Sign up to request clarification or add additional context in comments.

2 Comments

This works. Thanks! I was going to comment and say that this is too slow for my purposes but np.random.choice has a size parameter and the time scales really well in this parameter. (For future reference)
This solution also works for arrays of an arbitrary dimension btw.

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.