82

How can I know the (row, column) index of the minimum of a numpy array/matrix?

For example, if A = array([[1, 2], [3, 0]]), I want to get (1, 1)

Thanks!

2 Answers 2

157

Use unravel_index:

numpy.unravel_index(A.argmin(), A.shape)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but to comment this is surely a incredibly complex syntax for doing a simple stuff.
it really is quite standard syntax, simple even...its just one function extra function call beyond A.argmin(), which returns an index....
@linello, just create a function and reuse it, the complexity of the syntax doesn't matter
4

[Corrected typo]

Another simple solution is

ri, ci = A.argmin()//A.shape[1], A.argmin()%A.shape[1]

As numpy.argmin returns the index reading in row-major order


Yes, you are right, it was a typo, which worked for square matrix

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.