3

I have a 2d numpy array with a small range of different values. I want to retrieve a random index, but with a specific value. For example say this is the array:

arr = [[1,2,1,1,3],
       [4,3,4,1,1],
       [2,3,1,2,1],
       [1,2,1,1,2],
       [3,1,3,4,2]]

I want a random index of any value which is a 1, for example (2,2). The only way I have been able to do this so far is to take any random index, and then check afterwards if it contains the value I want and then redraw if it isn't. This would be ok for the above example, but I will need to retrieve many random indices from a large array.

Is there a method or algorithm for the procedure I am describing?

The application of this is to provide random pixels of a classified image to perform an accuracy assessment.

1
  • 1
    np.argwhere(arr==1)? Commented Jan 12, 2017 at 21:33

1 Answer 1

6

You convert your list to a numpy.array, then randomly pick one coordinate from a np.argwhere result:

import numpy as np
import random
random.choice(np.argwhere(np.array(arr)==value))
Sign up to request clarification or add additional context in comments.

Comments

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.