1

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?

1
  • Use np.where() , Commented Aug 2, 2020 at 9:30

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the suggestion btw, i improved it a bit like if u do np.where(matrix==1) the output will be in tuples and we can retrieve both values of row and column by tuple unpacking res=np.where(matrix==1) and (a,b)=res then we can use 'a' and 'b' individually

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.