Rebecca
Rebecca

Reputation: 123

randomly select position in array with condition

I have an array like this:

A = [[1,0,2,3],
     [2,0,1,1],
     [3,1,0,0]]

and I want to get the position of one of the cells with the value == 1 such as A[0][0] or A[1][2] and so on ...

So far I did this:

A = np.array([[1,0,2,3],
              [2,0,1,1],
              [3,1,0,0]])

B = np.where(A == 1)

C = []
for i in range(len(B[0])):
    Ca = [B[0][i], B[1][i]]
    C.append(Ca)

D = random.choice(C)

But now I want to reuse D for getting a cell value back. Like:

A[D] (which does not work) should return the same as A[1][2]

Does someone how to fix this or knows even a better solution?

Upvotes: 0

Views: 287

Answers (2)

sshashank124
sshashank124

Reputation: 32189

It seems you are trying to randomly select one of the cells where A is 1. You can use numpy for this all the way through instead of having to resort to for-loops

B = np.array(np.where(A == 1))

>>> B
array([[0, 1, 1, 2],
       [0, 2, 3, 1]])

Now to randomly select a column corresponding to one of the cells, we can use np.random.randint

column = np.random.randint(B.shape[1])
D = B[:, column]

>>> D
array([1, 2])  # corresponds to the second index pair in B

Now you can simply index into A using the tuple of D (to correpond to the dimensions' indices) as

>>> A[tuple(D)]
1

Upvotes: 0

Anurag A S
Anurag A S

Reputation: 731

This should work for you.

A = np.array([[1,0,2,3],
              [2,0,1,1],
              [3,1,0,0]])

B = np.where(A == 1)

C = []
for i in range(len(B[0])):
    Ca = [B[0][i], B[1][i]]
    C.append(Ca)


D = random.choice(C)
print(A[D[0]][D[1]])

This gives the output.

>>> print(A[D[0]][D[1]])
1

Since the value of D would be of the sort [X,Y], the value could be obtained from the matrix as A[D[0]][D[1]]

Upvotes: 1

Related Questions