numpy获得前n大元素下标

http://blog.sina.com.cn/s/blog_4df4d7440102vu6u.html

参考:http://stackoverflow.com/questions/10337533/a-fast-way-to-find-the-largest-n-elements-in-an-numpy-array
http://stackoverflow.com/questions/6910641/how-to-get-indices-of-n-maximum-values-in-a-numpy-array

EDIT: Modified to include Ashwini Chaudhary’s improvement.

>>> import heapq 
>>> import numpy 
>>> a = numpy.array([1, 3, 2, 4, 5]) 
>>> heapq.nlargest(3, range(len(a)), a.take) [4, 3, 1]

For regular Python lists:

>>> a = [1, 3, 2, 4, 5] >>> heapq.nlargest(3, range(len(a)), a.__getitem__) [4, 3, 1]
If you use Python 2, use xrange instead of range.

或者:
找出矩阵a的前3个最大的元素的index:
a.argsort()[-3:][::-1]

Perhaps heapq.nlargest
import numpy as np import heapq x = np.array([1,-5,4,6,-3,3]) z = heapq.nlargest(3,x)
Result:
>>> z [6, 4, 3]
If you want to find the indices of the n largest elements using bottleneck you could use bottleneck.argpartsort
>>> x = np.array([1,-5,4,6,-3,3]) >>> z = bottleneck.argpartsort(-x, 3)[:3] >>> z array([3, 2, 5]

猜你喜欢

转载自blog.csdn.net/qq_37873426/article/details/89365231