What\'s an efficient way, given a NumPy matrix (2D array), to return the minimum/maximum n
values (along with their indices) in the array?
Currently I h
Since there is no heap implementation in NumPy, probably your best guess is to sort the whole array and take the last n
elements:
def n_max(arr, n):
indices = arr.ravel().argsort()[-n:]
indices = (numpy.unravel_index(i, arr.shape) for i in indices)
return [(arr[i], i) for i in indices]
(This will probably return the list in reverse order compared to your implementation - I did not check.)
A more efficient solution that works with newer versions of NumPy is given in this answer.