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 0]
 [0 0 0 0 2 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 2 0 0 2 2 2 2 2 1 1 2 2 0 0 0]
 [0 0 0 0 2 1 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 1 1 2 2 0 2 1 1 1 1 1 1 1 2 0 0 0]
 [2 2 2 2 2 1 1 2 2 2 2 2 2 2 2 2 2 2 0 0 0 0 2 1 1 1 2 0 2 1 1 1 1 1 1 1 2 0 0 0]
 [2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 0 0 0 0 2 1 1 1 2 0 2 1 1 1 1 1 1 1 2 0 0 0]
 [2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 0 0 0 0 2 1 1 1 2 0 2 1 1 1 1 1 1 1 2 0 0 0]
 [2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 0 0 0 0 2 1 1 1 2 0 2 2 2 2 2 2 2 2 2 0 0 0]
 [2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 0 0 0 0 2 2 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]

And I want to pick a random position in the array which has a 1, how can I do this?


Solution 1:

Use np.argwhere and random.choice:

import numpy as np
import random

a = np.random.choice([0, 1, 2], (20, 20))
i = random.choice(np.argwhere(a == 1))

Solution 2:

You can use numpy.where to identify the coordinates of the cells of value 1, then pick one (or many) random indices from this output:

# test array
a = np.random.randint(0, 3, size=(15, 10))

# get coordinates where a == 1
coords = np.c_[np.where(a==1)]

# pick N random cells
N = 1
out = coords[np.random.choice(coords.shape[0], N, replace=False)]

# check
x,y = out[0]
assert a[x,y] == 1

example: (5, 3)

a:

array([[0, 1, 0, 1, 1, 2, 0, 2, 0, 0],
       [0, 2, 1, 2, 2, 0, 1, 1, 1, 1],
       [0, 1, 0, 0, 1, 2, 0, 2, 0, 1],
       [1, 2, 0, 1, 1, 1, 0, 2, 0, 2],
       [2, 0, 2, 0, 0, 0, 1, 1, 2, 0],
       [0, 1, 0, 1, 2, 2, 0, 1, 1, 1],
       [1, 2, 2, 2, 0, 2, 1, 0, 1, 2],
       [0, 0, 2, 0, 0, 0, 0, 0, 0, 2],
       [0, 2, 1, 1, 1, 0, 1, 1, 1, 0],
       [1, 2, 0, 1, 2, 0, 2, 0, 1, 2],
       [2, 1, 0, 1, 1, 0, 2, 2, 2, 2],
       [1, 2, 2, 2, 2, 2, 0, 1, 2, 2],
       [1, 2, 1, 0, 2, 2, 0, 2, 0, 0],
       [2, 0, 2, 2, 2, 0, 0, 0, 1, 2],
       [0, 1, 2, 2, 2, 1, 0, 0, 0, 0]])