How do I get indices of N maximum values in a NumPy array?

后端 未结 18 1441
长情又很酷
长情又很酷 2020-11-22 04:25

NumPy proposes a way to get the index of the maximum value of an array via np.argmax.

I would like a similar thing, but returning the indexes of the

18条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 05:04

    Use:

    >>> import heapq
    >>> import numpy
    >>> a = numpy.array([1, 3, 2, 4, 5])
    >>> heapq.nlargest(3, range(len(a)), a.take)
    [4, 3, 1]
    

    For regular Python lists:

    >>> a = [1, 3, 2, 4, 5]
    >>> heapq.nlargest(3, range(len(a)), a.__getitem__)
    [4, 3, 1]
    

    If you use Python 2, use xrange instead of range.

    Source: heapq — Heap queue algorithm

提交回复
热议问题