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

后端 未结 5 711
孤独总比滥情好
孤独总比滥情好 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:15

    I don't guarantee that this will be faster, but a better algorithm would rely on heapq.

    import heapq
    indices = heapq.nsmallest(10,np.nditer(arr),key=arr.__getitem__)
    

    This should work in approximately O(N) operations whereas using argsort would take O(NlogN) operations. However, the other is pushed into highly optimized C, so it might still perform better. To know for sure, you'd need to run some tests on your actual data.

提交回复
热议问题