Numpy minimum in (row, column) format
Asked Answered
K

2

80

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!

Kurbash answered 12/7, 2010 at 16:6 Comment(0)
I
150

Use unravel_index:

numpy.unravel_index(A.argmin(), A.shape)
Idzik answered 12/7, 2010 at 16:13 Comment(3)
Thanks, but to comment this is surely a incredibly complex syntax for doing a simple stuff.Duchy
it really is quite standard syntax, simple even...its just one function extra function call beyond A.argmin(), which returns an index....Specification
@linello, just create a function and reuse it, the complexity of the syntax doesn't matterCrepuscule
H
3

[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

Hochman answered 27/3, 2018 at 8:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.