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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?

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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]])

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.