2

I have a numpy array of shape (4, 7) like this:

array([[ 1,  4,  5,  7,  8,  6,  7]
       [ 2, 23,  2,  4,  8, 94,  2],
       [ 1,  5,  6,  7, 10, 15, 20],
       [ 3,  9,  2,  7,  6,  5,  4]])

I would like to get the index of the highest element, i.e. 94, in a form like: first row fifth column. Thus the output should be a numpy array ([1,5]) (matlab-style).

1 Answer 1

3

You get the index of the maximum index using arr.argmax() but to get the actual row and column you must use np.unravel_index as below:

import numpy as np

arr = np.array([[ 1,  4,  5,  7,  8,  6,  7],
                [ 2, 23,  2,  4,  8, 94,  2],
                [ 1,  5,  6,  7, 10, 15, 20],
                [ 3,  9,  2,  7,  6,  5,  4]])

maximum = np.unravel_index(arr.argmax(), arr.shape)

print(maximum)
# (1, 5)

You have to use np.unravel_index as by default np.argmax will return the index from a flattened array (which in your case would be index 12).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.