1

Is it possible to convert the largest numpy array offset to a tuple?

So for example, if "array" was:

[[1 2 3 6 8],
 [2 4 1 1 0],
 [0 0 0 20 0]]

Then the np.max(array) would return 20 and it's position/ offset is array[2][3].

Is it possible to turn array[2][3] into tuple = (2,3)?

Thank you for the input.

Landon G
  • 819
  • 2
  • 12
  • 31

2 Answers2

3

you are looking for unravel_index and argmax

import numpy as np

a = np.array([[1 2 3 6 8],
              [2 4 1 1 0],
              [0 0 0 20 0]])

np.unravel_index( a.argmax() , a.shape)
Gabriel M
  • 1,486
  • 4
  • 17
  • 25
1

To find all max value indices:

np.argwhere(np.max(a) == a)
# array([[2, 3]])

Then you can get the first max value index:

np.argwhere(np.max(a) == a)[0]
# array([2, 3])

And convert it to tuple if needed:

tuple(np.argwhere(np.max(a) == a)[0])
# (2, 3)
Psidom
  • 209,562
  • 33
  • 339
  • 356