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

Using the 'unique' function is a very clean way to do it, but likely not the fastest:

k = array([[ 35,  48,  63],
           [ 60,  77,  96],
           [ 91, 112, 135]])
i = numpy.unique(k)[-2]

for the second largest


You can flatten the matrix and then sort it:

>>> k = np.array([[ 35,  48,  63],
...        [ 60,  77,  96],
...        [ 91, 112, 135]])
>>> flat=k.flatten()
>>> flat.sort()
>>> flat
array([ 35,  48,  60,  63,  77,  91,  96, 112, 135])
>>> flat[-2]
112
>>> flat[-3]
96

As said, np.partition should be faster (at most O(n) running time):

np.partition(k.flatten(), -2)[-2]

should return the 2nd largest element. (partition guarantees that the numbered element is in position, all elements before are smaller, and all behind are bigger).

Tags:

Python

Numpy