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

后端 未结 18 1443
长情又很酷
长情又很酷 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:11

    Here's a more complicated way that increases n if the nth value has ties:

    >>>> def get_top_n_plus_ties(arr,n):
    >>>>     sorted_args = np.argsort(-arr)
    >>>>     thresh = arr[sorted_args[n]]
    >>>>     n_ = np.sum(arr >= thresh)
    >>>>     return sorted_args[:n_]
    >>>> get_top_n_plus_ties(np.array([2,9,8,3,0,2,8,3,1,9,5]),3)
    array([1, 9, 2, 6])
    

提交回复
热议问题