Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy get index of row with second-largest value

Tags:

python

numpy

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?

like image 258
Paradox Avatar asked Feb 02 '19 17:02

Paradox


People also ask

How do you find the index of the second highest value in an array in Python?

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.

How do I find the second largest number in a NumPy array?

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.

How do I get indices of N maximum values 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.

What does argmax do in NumPy?

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.


2 Answers

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.

like image 170
dangom Avatar answered Sep 19 '22 17:09

dangom


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.

like image 28
Divakar Avatar answered Sep 21 '22 17:09

Divakar