How do I get indices of N maximum values in a NumPy array?

后端 未结 18 1514
长情又很酷
长情又很酷 2020-11-22 04:25

NumPy proposes a way to get the index of the maximum value of an array via np.argmax.

I would like a similar thing, but returning the indexes of the

18条回答
  •  猫巷女王i
    2020-11-22 04:55

    This code works for a numpy 2D matrix array:

    mat = np.array([[1, 3], [2, 5]]) # numpy matrix
     
    n = 2  # n
    n_largest_mat = np.sort(mat, axis=None)[-n:] # n_largest 
    tf_n_largest = np.zeros((2,2), dtype=bool) # all false matrix
    for x in n_largest_mat: 
      tf_n_largest = (tf_n_largest) | (mat == x) # true-false  
    
    n_largest_elems = mat[tf_n_largest] # true-false indexing 
    

    This produces a true-false n_largest matrix indexing that also works to extract n_largest elements from a matrix array

提交回复
热议问题