2

I have a large 2-dimensional Numpy array which looks a bit like this, and I want to find the indexes of the highest number in the array.

[[0.09911875 0.087047   0.07395894 ... 0.10334793 0.10507131 0.10572167]
 [0.09951172 0.08808007 0.07559184 ... 0.0953996  0.09637988 0.09686002]
 [0.09908096 0.08856899 0.07680183 ... 0.08633772 0.08709209 0.08753099]
 ...
 [0.16518855 0.1658697  0.16564748 ... 0.16108064 0.15890269 0.15795946]
 [0.16250964 0.1616099  0.16255783 ... 0.15931444 0.15753458 0.15655452]
 [0.16211866 0.15905266 0.15936445 ... 0.15891747 0.15701842 0.15521818]]

So far, I've tried to use numpy.where() as that function returns a tuple of coordinates but I've only been able to receive an array of tuples, but I want one tuple, the coordinates of the highest number. I've also tried to use other Numpy methods like np.amax, np.max, and np.where but to no success.


To further explain, if you had a small 2D array like this. The largest number is 9.99 and the indexes of the highest number will be (2,2).

[[2.18, 4.01, 3.49, 1.22]
 [2.34, 5.23, 5.11, 4.23]
 [1.23, 3.42, 9.99, 6.02]
 [2.08, 4.01, 3.49, 1.22]]
TriThomas
  • 383
  • 2
  • 16

4 Answers4

3

You could use the numpy.argmax method combined with numpy.unravel:

Here's a minimal working example:

import numpy as np

# create random array
a = np.random.random((8, 8))

# find indexes of the maximum value in this array
np.unravel_index(a.argmax(), a.shape)
# > [4, 3]
bglbrt
  • 2,018
  • 8
  • 21
0

You can use:

(x.argmax() // x.shape[1], x.argmax() % x.shape[1])

(2, 2)

Thomas Schillaci
  • 2,348
  • 1
  • 7
  • 19
0

All you need to do is to convert the index found by np.argmax() into your matrix indexes. This answer shows how to do that.

This is how you could do it.

import numpy as np


a = np.array([[1, 2, 3], [3, 4, 7], [4, 5, 1]])

max_index = np.argmax(a)
tuple_result = (max_index // a.shape[0], max_index % a.shape[1])
print(tuple_result)

jpnadas
  • 774
  • 6
  • 17
-1

If x is the array then you can try

np.where(x==np.max(x))

This will give you the i,j positions in the array.

Ricky
  • 2,662
  • 5
  • 25
  • 57