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

后端 未结 18 1515
长情又很酷
长情又很酷 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条回答
  •  猫巷女王i
    2020-11-22 05:09

    If you don't care about the order of the K-th largest elements you can use argpartition, which should perform better than a full sort through argsort.

    K = 4 # We want the indices of the four largest values
    a = np.array([0, 8, 0, 4, 5, 8, 8, 0, 4, 2])
    np.argpartition(a,-K)[-K:]
    array([4, 1, 5, 6])
    

    Credits go to this question.

    I ran a few tests and it looks like argpartition outperforms argsort as the size of the array and the value of K increase.

提交回复
热议问题