Reputation: 3509
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.
Upvotes: 4
Views: 4048
Reputation: 19169
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
Upvotes: 0
Reputation: 32511
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
Upvotes: 2