문제

I have an array as such:

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

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

So basically, np.argmin() with a condition for the second column to be equal to -1 (or any other value for that matter).

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

I'm pretty sure there's a simple way, but I can't find it.

도움이 되었습니까?

해결책

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

다른 팁

np.argwhere(a[:,1] == -1)[np.argmin(a[a[:, 1] == -1, 0])]

This is not efficient but if you have a relatively small array and want a one-line solution:

>>> 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top