SSPlusUltra
SSPlusUltra

Reputation: 13

How to find row number and column number of a specific element in a multi dimensional array created with numpy?

In a multi-dimensional array created using numpy in python like

matrix=np.array[[0,0,0,0,0], [0,0,0,0,1], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] 

if we were to treat it as matrix. Is there any way to find the row number and column number of element '1' or any other specific element inside the matrix?

Upvotes: 1

Views: 971

Answers (1)

Valdi_Bo
Valdi_Bo

Reputation: 30971

One of possible solutions is to use np.argwhere:

np.argwhere(matrix == 1)

but note that your array can contain multiple elements with just this value, so it returns a 2-D array, where each row contains indices of each element found.

If you want only the first such element, run:

np.argwhere(matrix == 1)[0]

This time you will get a 1-D array, containing 2 element (row and column number).

Upvotes: 3

Related Questions