Quickest way to find the nth largest value in a numpy Matrix

前端 未结 6 1917
孤独总比滥情好
孤独总比滥情好 2020-12-29 06:56

There are lots of solutions to do this for a single array, but what about a matrix, such as:

>>> k
array([[ 35,  48,  63],
       [ 60,  77,  96],
          


        
6条回答
  •  余生分开走
    2020-12-29 07:33

    Another way of doing this when repeating elements are presented in the array at hand. If we have something like

    a = np.array([[1,1],[3,4]])
    

    then the second largest element will be 3, not 1.

    Alternatively, one could use the following snippet:

    second_largest = sorted(list(set(a.flatten().tolist())))[-2]
    

    First, flatten matrix, then only leave unique elements, then back to the mutable list, sort it and take the second element. This should return the second largest element from the end even if there are repeating elements in the array.

提交回复
热议问题