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?
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.
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.
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...
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With