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

后端 未结 5 712
孤独总比滥情好
孤独总比滥情好 2021-02-05 02:57

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 i

5条回答
  •  孤独总比滥情好
    2021-02-05 03:00

    Since this question was posted, numpy has updated to include a faster way of selecting the smallest elements from an array using argpartition. It was first included in Numpy 1.8.

    Using snarly's answer as inspiration, we can quickly find the k=3 smallest elements:

    In [1]: import numpy as np
    
    In [2]: arr = np.array([1, 3, 2, 4, 5])
    
    In [3]: k = 3
    
    In [4]: ind = np.argpartition(arr, k)[:k]
    
    In [5]: ind
    Out[5]: array([0, 2, 1])
    
    In [6]: arr[ind]
    Out[6]: array([1, 2, 3])
    

    This will run in O(n) time because it does not need to do a full sort. If you need your answers sorted (Note: in this case the output array was in sorted order but that is not guaranteed) you can sort the output:

    In [7]: sorted(arr[ind])
    Out[7]: array([1, 2, 3])
    

    This runs on O(n + k log k) because the sorting takes place on the smaller output list.

提交回复
热议问题