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

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

    I think the most time efficiency way is manually iterate through the array and keep a k-size min-heap, as other people have mentioned.

    And I also come up with a brute force approach:

    top_k_index_list = [ ]
    for i in range(k):
        top_k_index_list.append(np.argmax(my_array))
        my_array[top_k_index_list[-1]] = -float('inf')
    

    Set the largest element to a large negative value after you use argmax to get its index. And then the next call of argmax will return the second largest element. And you can log the original value of these elements and recover them if you want.

提交回复
热议问题