Reputation: 2790
I have a numpy array and I wan to have the index of the top value sorted that are superior to 0 for instance:
[-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7]
And I want to have:
[6, 1, 4, 5]
I can do it using a function I implemented but I guess for this kind of task there is something already implemented in Numpy.
Upvotes: 2
Views: 111
Reputation: 6357
Use np.where()
.
d > 0.0
generates a boolean mask and where
fetches all the values where the mask is true.
>>> d=np.array([-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7])
>>> r=np.where( d > 0)
>>> s=sorted(r[0].tolist(), key=lambda x:d[x], reverse=True)
>>> s
[6L, 1L, 4L, 5L]
EDIT
Here's what I mean by mask.
>>> mask = d > 0
>>> mask
array([False, True, False, False, True, True, True], dtype=bool)
Upvotes: 1
Reputation: 221754
Here's a vectorized approach -
idx = np.where(A>0)[0]
out = idx[A[idx].argsort()[::-1]]
Sample run -
In [37]: A = np.array([-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7])
In [38]: idx = np.where(A>0)[0]
In [39]: idx[A[idx].argsort()[::-1]]
Out[39]: array([6, 1, 4, 5])
Upvotes: 2
Reputation: 31181
You can also do:
L = [-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7]
[L.index(i) for i in sorted(filter(lambda x: x>0, L), reverse=True)]
Out[72]: [6, 1, 4, 5]
Upvotes: 3
Reputation: 16081
You can implement with np.where
a = np.array([-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7])
np.where(a > 0)[0].tolist()
Result
[1, 4, 5, 6]
The result of np.where(a > 0)
is in the form of tuple of numpy array. So can converted into list with using tolist()
Upvotes: 2