Efficient way to take the minimum/maximum n values and indices from a matrix using NumPy

前端 未结 3 1974
挽巷
挽巷 2020-11-30 08:09

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

3条回答
  •  有刺的猬
    2020-11-30 08:46

    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.

提交回复
热议问题