[Numpy-discussion] Find indices of largest elements

Nikolaus Rath Nikolaus at rath.org
Wed Apr 14 15:39:40 EDT 2010


Keith Goodman <kwgoodman at gmail.com> writes:
> On Wed, Apr 14, 2010 at 8:49 AM, Keith Goodman <kwgoodman at gmail.com> wrote:
>> On Wed, Apr 14, 2010 at 8:16 AM, Nikolaus Rath <Nikolaus at rath.org> wrote:
>>> Hello,
>>>
>>> How do I best find out the indices of the largest x elements in an
>>> array?
>>>
>>> Example:
>>>
>>> a = [ [1,8,2], [2,1,3] ]
>>> magic_function(a, 2) == [ (0,1), (1,2) ]
>>>
>>> Since the largest 2 elements are at positions (0,1) and (1,2).
>>
>> Here's a quick way to rank the data if there are no ties and no NaNs:
>
> ...or if you need the indices in order:
>
>>> shape = (3,2)
>>> x = np.random.rand(*shape)
>>> x
> array([[ 0.52420123,  0.43231286],
>        [ 0.97995333,  0.87416228],
>        [ 0.71604075,  0.66018382]])
>>> r = x.reshape(-1).argsort().argsort()

I don't understand why this works. Why do you call argsort() twice?
Doesn't that give you the indices of the sorted indices?


Thanks,

   -Nikolaus

-- 
 »Time flies like an arrow, fruit flies like a Banana.«

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C




More information about the NumPy-Discussion mailing list