# python 如何在numpy數組中獲取N個最大值的索引？

``````>>> a
array([9, 4, 4, 3, 3, 9, 0, 4, 6, 0])
>>> ind = np.argpartition(a, -4)[-4:]
>>> ind
array([1, 5, 8, 0])
>>> a[ind]
array([4, 9, 6, 9])
``````

`argsort`不同的`argsort` ，這個函數在最壞的情況下以線性時間運行，但是返回的索引沒有被排序，從評估`a[ind]`的結果可以看出。 如果您也需要，請在之後進行分類：

``````>>> ind[np.argsort(a[ind])]
array([1, 8, 5, 0])
``````

python numpy

Numpy提出了一種通過`np.argmax`數組最大值索引的`np.argmax`

``````idx = (-arr).argsort()[:n]
``````

``````K = 4 # we want the indeces 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])
``````

`bottleneck`具有部分排序功能，如果為了獲得N個最大值而排序整個數組的代價太大。

``````from operator import itemgetter
from heapq import nlargest
result = nlargest(N, enumerate(your_list), itemgetter(1))
``````

``````def max_indices(arr, k):
'''
Returns the indices of the k first largest elements of arr
(in descending order in values)
'''
assert k <= arr.size, 'k should be smaller or equal to the array size'
arr_ = arr.astype(float)  # make a copy of arr
max_idxs = []
for _ in range(k):
max_element = np.max(arr_)
if np.isinf(max_element):
break
else:
idx = np.where(arr_ == max_element)
max_idxs.append(idx)
arr_[idx] = -np.inf
return max_idxs
``````

``````In [0]: A = np.array([[ 0.51845014,  0.72528114],
[ 0.88421561,  0.18798661],
[ 0.89832036,  0.19448609],
[ 0.89832036,  0.19448609]])
In [1]: max_indices(A, 8)
Out[1]:
[(array([2, 3], dtype=int64), array([0, 0], dtype=int64)),
(array([1], dtype=int64), array([0], dtype=int64)),
(array([0], dtype=int64), array([1], dtype=int64)),
(array([0], dtype=int64), array([0], dtype=int64)),
(array([2, 3], dtype=int64), array([1, 1], dtype=int64)),
(array([1], dtype=int64), array([1], dtype=int64))]

In [2]: A[max_indices(A, 8)[0]][0]
Out[2]: array([ 0.89832036])
``````

python   numpy