在不排序的情况下获取numpy数组中N个最大值的索引? [英] Get indices of N maximum values in a numpy array without sorting them?

查看:191
本文介绍了在不排序的情况下获取numpy数组中N个最大值的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与这一问题非常相似:

My question is very similar to this one: How to get indices of N maximum values in a numpy array?

但是我想以找到索引的相同顺序来获取索引.

But I would like to get the indices in the same order I find them.

让我们以该问题中标记的示例作为正确的解决方案:

Let's take the example marked in that question as the correct solution:

import numpy as np
arr = np.array([1, 3, 2, 4, 5])
arr.argsort()[-3:][::-1]

array([4, 3, 1])

我正在寻找的结果应该是:

The result I'm looking for instead should be like:

array([1, 3, 4])

推荐答案

使用根据需要调整k索引.

注意:返回的索引不能保证按排序顺序"进行-只是索引k之后的任何内容大于排序数组中位置k的值.

NOTE: returned indices are not guaranteed to be in the "sorted order" - just that anything past index k is larger than the value at position k in the sorted array.

注2:如果您确实需要对返回的索引进行排序,则只需在上述命令中添加numpy.sort()即可:

NOTE 2: If you do need the returned indices to be sorted themselves, then simply add a numpy.sort() to the above command:

np.sort(np.argpartition(arr, len(arr) - k)[-k:])

numpy.argpartition()在整个sort上提供了显着的性能提升,尤其是对于大型arr.在上面的示例中,您仅对所选索引(不是全部)进行完整排序.

numpy.argpartition() provides significant performance gains over full sort especially for large arr. In the above example you do a full sort only over the selected indices (not all).

这篇关于在不排序的情况下获取numpy数组中N个最大值的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆