I am aware of how to get the index of the row containing the largest element with this snippet:
np.argmax(np.max(x, axis=0))
However, how could I get the index of the second largest row? I figure that I can cut off a row of x then try again, but is there a more elegant solution to this which can be scaled for the 3rd largest, 4th, etc?
Now, to get the second largest element we need to get the second element starting from the right. To do that, we can use negative indexing: To get the first element starting from the right, we need to use the index of -1. To get the second element starting from the right, we need to use the index of -2.
You should find the maximum in the list and save its index. Then remove it from the list using the remove() function and then find the maximum of the new list (with the original maximum value removed) and that will be your second highest element.
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.
Returns the indices of the maximum values along an axis. Input array. By default, the index is into the flattened array, otherwise along the specified axis.
You can use np.argsort(np.max(x, axis=0))[-2]
.
This scales to any index you want by changing the slicing index from -2
to -index
.
Use argsort
on flattened version and then use np.unravel_index
to get row, col indices -
row,col = np.unravel_index(np.argsort(x.ravel()),x.shape)
Then, the largest row index would be row[-1]
, second largest in row[-2]
and so on. Similarly, for columns, use col
.
So, for convenience, you can flip the elements and use :
row,col = row[::-1],col[::-1]
Then, the largest ones would be at [0]
, second largest at [1]
and so on.
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