Numpy minimum in (row, column) format

PythonArraysNumpyMinimum

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

Use unravel_index:

numpy.unravel_index(A.argmin(), A.shape)

Solution 2 - Python

[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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyassinView Question on Stackoverflow
Solution 1 - PythonPhilippView Answer on Stackoverflow
Solution 2 - PythonNikesh BajajView Answer on Stackoverflow