Find the index of the k smallest values of a numpy array

后端 未结 4 784
南旧
南旧 2020-12-07 14:44

In order to find the index of the smallest value, I can use argmin:

import numpy as np
A = np.array([1, 7, 9, 2, 0.1, 17, 17, 1.5])
print A.arg         


        
4条回答
  •  日久生厌
    2020-12-07 15:03

    For n-dimentional arrays, this function works well. The indecies are returned in a callable form. If you want a list of the indices to be returned, then you need to transpose the array before you make a list.

    To retrieve the k largest, simply pass in -k.

    def get_indices_of_k_smallest(arr, k):
        idx = np.argpartition(arr.ravel(), k)
        return tuple(np.array(np.unravel_index(idx, arr.shape))[:, range(min(k, 0), max(k, 0))])
        # if you want it in a list of indices . . . 
        # return np.array(np.unravel_index(idx, arr.shape))[:, range(k)].transpose().tolist()
    

    Example:

    r = np.random.RandomState(1234)
    arr = r.randint(1, 1000, 2 * 4 * 6).reshape(2, 4, 6)
    
    indices = get_indices_of_k_smallest(arr, 4)
    indices
    # (array([1, 0, 0, 1], dtype=int64),
    #  array([3, 2, 0, 1], dtype=int64),
    #  array([3, 0, 3, 3], dtype=int64))
    
    arr[indices]
    # array([ 4, 31, 54, 77])
    
    %%timeit
    get_indices_of_k_smallest(arr, 4)
    # 17.1 µs ± 651 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    

提交回复
热议问题