Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

numpy

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],        [ 91, 112, 135]]) 

You can use k.max(), but of course this only returns the highest value, 135. What if I want the second or third?

like image 594
thefoxrocks Avatar asked Oct 17 '15 00:10

thefoxrocks


People also ask

How do you find the N largest value in a NumPy array?

For getting n-largest values from a NumPy array we have to first sort the NumPy array using numpy. argsort() function of NumPy then applying slicing concept with negative indexing. Return: [index_array, ndarray] Array of indices that sort arr along the specified axis.

How do you find the nth largest number in an array in Python?

Suppose we have an unsorted array, we have to find the kth largest element from that array. So if the array is [3,2,1,5,6,4] and k = 2, then the result will be 5. We will sort the element, if the k is 1, then return last element, otherwise return array[n – k], where n is the size of the array.

How do you find the nth largest value?

The LARGE function is an easy way to get the nth largest value in a range: = LARGE ( range , 1 ) // 1st largest = LARGE ( range , 2 ) // 2nd largest = LARGE ( range , 3 ) // 3rd largest In this example, we can use the LARGE function to get a highest...

Which function helps find the maximum value number in NumPy?

maximum() function is used to find the element-wise maximum of array elements. It compares two arrays and returns a new array containing the element-wise maxima.


1 Answers

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).

like image 164
serv-inc Avatar answered Oct 05 '22 15:10

serv-inc