I have need the N minimum (index) values in a numpy array

astrochris picture astrochris · May 29, 2013 · Viewed 50k times · Source

Hi I have an array with X amount of values in it I would like to locate the indexs of the ten smallest values. In this link they calculated the maximum effectively, How to get indices of N maximum values in a numpy array? however I cant comment on links yet so I'm having to repost the question.

I'm not sure which indices i need to change to achieve the minimum and not the maximum values. This is their code

In [1]: import numpy as np

In [2]: arr = np.array([1, 3, 2, 4, 5])

In [3]: arr.argsort()[-3:][::-1]
Out[3]: array([4, 3, 1]) 

Answer

petrichor picture petrichor · May 29, 2013

If you call

arr.argsort()[:3]

It will give you the indices of the 3 smallest elements.

array([0, 2, 1], dtype=int64)

So, for n, you should call

arr.argsort()[:n]