Quantcast
Channel: Get indices of N maximum values in a numpy array without sorting them? - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by AGN Gazer for Get indices of N maximum values in a numpy array without sorting them?

$
0
0

Use numpy.argpartition():

k = 3np.argpartition(arr, len(arr) - k)[-k:]

Adjust k index to whatever you need.

NOTE: returned indices are not guaranteed to be in the "sorted order" - just that anything past index k is larger than the value at position k in the sorted array.

NOTE 2: If you do need the returned indices to be sorted themselves, then simply add a numpy.sort() to the above command:

np.sort(np.argpartition(arr, len(arr) - k)[-k:])

numpy.argpartition() provides significant performance gains over full sort especially for large arr. In the above example you do a full sort only over the selected indices (not all).


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>