[Numpy-discussion] argmax for top N elements

Keith Goodman kwgoodman@gmail....
Wed Jun 22 14:18:22 CDT 2011


On Wed, Jun 22, 2011 at 12:08 PM, RadimRehurek <RadimRehurek@seznam.cz> wrote:
>> Date: Wed, 22 Jun 2011 11:30:47 -0400
>> From: Alex Flint <alex.flint@gmail.com>
>> Subject: [Numpy-discussion] argmax for top N elements
>>
>> Is it possible to use argmax or something similar to find the locations of
>> the largest N elements in a matrix?
>
> I would also be interested in an O(N) argmax/argmin for indices of top k values in an array. I'm currently using argsort[:k] in a performance sensitive part and it's not ideal.
>

You can try argpartsort from the bottleneck package:

	>> a = np.random.rand(100000)
	>> k = 10
	>> timeit a.argsort()[:k]
	100 loops, best of 3: 11.2 ms per loop
        >> import bottleneck as bn
	>> timeit bn.argpartsort(a, k)[:k]
	1000 loops, best of 3: 1.29 ms per loop

Output of argpartsort is not ordered:

	>> a.argsort()[:k]
	   array([97239, 21091, 25130, 41638, 62323, 57419,  4381, 34905,
94572, 25935])
	>> bn.argpartsort(a, k)[:k]
	   array([21091, 62323, 25130, 97239, 41638, 57419,  4381, 34905,
94572, 25935])


More information about the NumPy-Discussion mailing list