-1

I have a 2D Numpy Array - arr2D = numpy.array([[11, 12, 13], [14, 15, 16], [17, 15, 11], [12, 14, 15]]).

  • I want to find the first 3 largest values in above 2D array ==> 17, 16, 15
  • I also want to get row index number of these values in an array ==> row index = 2,1,3

Can someone show me how to achieve this?

Thanks.

2 Answers2

0

You could sort the flattened array with np.argsort then divide the global indices by the number of columns to retrieve the row index:

>>> arg = (-x).flatten().argsort()
array([ 6,  5,  4,  7, 11,  3, 10,  2,  1,  9,  0,  8])

>>> arg[:3] // 3
array([2, 1, 1])

Which is row 2 (17), row 1 (16), and row 1 again (15).

Ivan
  • 34,531
  • 8
  • 55
  • 100
0

With arr2D.max(axis=1) you get the maximum value of every subarray.

And here: How do I get indices of N maximum values in a NumPy array? is the solution how to get the indices of the N largest elements.

Mike S
  • 180
  • 1
  • 15
  • Thanks for this, I went through answers and https://stackoverflow.com/a/23734295/7035448 is best speed wise and comparision of speed is here https://stackoverflow.com/a/64724784/7035448 +1 – eroot163pi Jul 30 '21 at 07:39
  • OP doesn't seem to be looking for maximum *per* subarray, but rather the largest elements irrespective of subarrays. – Ivan Jul 30 '21 at 09:12
  • If so, you're answer is the better match. But as you encountered in your answer, then the provided example [2, 1, 3] is wrong and should be [2, 1, 1]. I think OP has to clearify some things – Mike S Jul 30 '21 at 09:37