1

I am trying to find out the index of the minimum value in each row and I am using below code.

#code
import numpy as np
C = np.array([[1,2,4],[2,2,5],[4,3,3]])
ind = np.where(C == C.min(axis=1).reshape(len(C),1))
ind

#output
(array([0, 1, 1, 2, 2], dtype=int64), array([0, 0, 1, 1, 2], dtype=int64))

but the problem it is returning all indices of minimum values in each row. but I want only the first occurrence of minimum values. like

(array([0, 1, 2], dtype=int64), array([0, 0, 1], dtype=int64))
2
  • 1
    Use argmin : C.argmin(1) and np.arange(C.shape[0]) for the row indices. Commented Apr 18, 2017 at 20:35
  • Divakar Thanks, please add it in answer I will mark it as the correct answer. Commented Apr 18, 2017 at 20:38

1 Answer 1

3

If you want to use comparison against the minimum value, we need to use np.min and keep the dimensions with keepdims set as True to give us a boolean array/mask. To select the first occurance, we can use argmax along each row of the mask and thus have our desired output.

Thus, the implementation to get the corresponding column indices would be -

(C==C.min(1, keepdims=True)).argmax(1)

Sample step-by-step run -

In [114]: C   # Input array
Out[114]: 
array([[1, 2, 4],
       [2, 2, 5],
       [4, 3, 3]])

In [115]: C==C.min(1, keepdims=1) # boolean array of min values
Out[115]: 
array([[ True, False, False],
       [ True,  True, False],
       [False,  True,  True]], dtype=bool)

In [116]: (C==C.min(1, keepdims=True)).argmax(1) # argmax to get first occurances
Out[116]: array([0, 0, 1])

The first output of row indices would simply be a range array -

np.arange(C.shape[0])

To achieve the same column indices of first occurance of minimum values, a direct way would be to use np.argmin -

C.argmin(axis=1)
Sign up to request clarification or add additional context in comments.

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.