If i have an array like this
a = np.array([[False, False, False, False, False, False, False, False, False, False],[False, False, False, False, False, False, False, False, False, False],[False, False, False, True, True, False, False, False, False, False],
I tried np.random.choice but it doesnt work for 1_D arrays :(
CodePudding user response:
A possible solution is to loop through different indexes until you find a match
E.g.
import random
index_0 = 0
index_1 = 0
found = False
while not found:
temp_i0 = random.randint(len(array))
temp_i1 = random.randint(len(array[0]))
if array[temp_i0][temp_i1]:
index_0 = temp_i0
index_1 = temp_i1
found = True
CodePudding user response:
You can use np.random.choice
with a little extra work:
You can use:
np.unravel_index(np.random.choice(np.flatnonzero(a)), a.shape)
In words:
Flatten a
and find the indices where a
is nonzero in a
using np.flatnonzero
. Then, pick a random index among nonzero indices using np.random.choice
. This gives us a random index in the flattened array, so we convert it back into 2D row/column coordinates using np.unravel_index
.