Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of n largest elements in a list or np.array, Python

Tags:

Is there a built-in function or a very simple way of finding the index of n largest elements in a list or a numpy array?

K = [1,2,2,4,5,5,6,10] 

Find the index of the largest 5 elements?

I count the duplicates more than once, and the output should be a list of the indices of those largest numbers

like image 701
Logan Yang Avatar asked Jun 02 '13 00:06

Logan Yang


1 Answers

Maybe something like:

>>> K [4, 5, 1, 6, 2, 5, 2, 10] >>> sorted(range(len(K)), key=lambda x: K[x]) [2, 4, 6, 0, 1, 5, 3, 7] >>> sorted(range(len(K)), key=lambda x: K[x])[-5:] [0, 1, 5, 3, 7] 

or using numpy, you can use argsort:

>>> np.argsort(K)[-5:] array([0, 1, 5, 3, 7]) 

argsort is also a method:

>>> K = np.array(K) >>> K.argsort()[-5:] array([0, 1, 5, 3, 7]) >>> K[K.argsort()[-5:]] array([ 4,  5,  5,  6, 10]) 
like image 177
DSM Avatar answered Oct 05 '22 03:10

DSM