Issue
I have a list like a=[3,5,7,12,4,1,5]
and need to get the indices of the top K(=3)
elements of this list, in the order of the elements. So in this case, result should be
[3,2,1]
since top 3 elements are 12, 7, 5
(last one is tie so first index is returned).
What is the simplest way to get this?
Solution
As this is tagged numpy, you can use numpy.argsort
on the opposite values (for reverse sorting), then slice to get the K
desired values:
a = np.array([3,5,7,12,4,18,1,5,18])
K = 3
out = np.argsort(-a)[:K]
output: array([3, 2, 1])
If you want the indices in order of the original array but not necessarily sorted themselves in order of the values, you can also use numpy.argpartition
:
out = np.argpartition(a, K)[-K:]
Answered By - mozway
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.