0

How do I find the N highest values of an vector? Let´s say I´ve got a vector:

arr = np.array([12.5, 13.6, −9.1, 17.5, 15.3, 10.5])

And N = 3

the output should then be:

np.array([13.6,17.5,15.3])

So the 3 highest values of arr are kept in the same order.

if N=4 the output should be:

np.array([12.5,13.6,17.5,15.3])
blhsing
  • 91,368
  • 6
  • 71
  • 106
CEFOG
  • 89
  • 8

1 Answers1

1

You might like heapq.nlargest() method. It allows you to take n largest elements of any collections using linear time. I.e. you don't need to sort your original collection spending O(n*log n) time.

import heapq

n = 4
print(np.array(heapq.nlargest(n, arr)))
Ivan Velichko
  • 6,348
  • 6
  • 44
  • 90