Numpy: get index of smallest value based on conditions

I have an array as such:

array([[ 10, -1],
       [ 3,  1],
       [ 5, -1],
       [ 7,  1]])

I want to get the index of the row with the smallest value in the first column and -1 in the second.

Basically, np.argmin()with the condition that the second column be -1 (or any other value in this regard).

In my example, I would like to get 2which is an index [ 5, -1].

I am sure there is an easy way, but I cannot find it.

+4
source share
3 answers
import numpy as np

a = np.array([
    [10, -1],
    [ 3,  1],
    [ 5, -1],
    [ 7,  1]])

mask = (a[:, 1] == -1)

arg = np.argmin(a[mask][:, 0])
result = np.arange(a.shape[0])[mask][arg]
print result
+1
source
np.argwhere(a[:,1] == -1)[np.argmin(a[a[:, 1] == -1, 0])]
+2
source

, :

>>> a = np.array([[ 10, -1],
...               [ 3,  1],
...               [ 5, -1],
...               [ 7,  1]])
>>> [i for i in np.argsort(a[:, 0]) if a[i, 1] == -1][0]
2
0

Source: https://habr.com/ru/post/1530274/


All Articles