Get indices of top N values in 2D numpy ndarray or numpy matrix

后端 未结 2 829
南旧
南旧 2020-12-21 03:59

I have an array of N-dimensional vectors.

data = np.array([[5, 6, 1], [2, 0, 8], [4, 9, 3]])

In [1]: data
Out[1]:
array([[5, 6, 1],
             


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-21 04:35

    As a slight improvement over the otherwise very good answer by DSM, instead of using np.argsort(), it is more efficient to use np.argpartition() if the order of the N greatest is of no consequence.

    Partitioning an array arr with index i rearranges the elements such that the element at index i is the ith greatest, while those on the left are greater and on the right are lesser. The partitions on the left and right are not necessarily sorted. This has the advantage that it runs in linear time.

提交回复
热议问题