3
import numpy as np
a = np.array([[[ 0.25,  0.10 ,  0.50 ,  0.15],
           [ 0.50,  0.60 ,  0.70 ,  0.30]],
          [[ 0.25,  0.50 ,  0.20 ,  0.70],
           [ 0.80,  0.10 ,  0.50 ,  0.15]]])

I need to find the row and column of the max value in a[i]. If i=0, a[0,1,2] is max, so I need to code a method that gives [1,2] as the output for max in a[0]. Any pointers, please? NB: np.argmax flattens the a[i] 2D array and when axis=0 is used, it gives the index of max in each row of a[0]

1
  • I would suggest looking at numpy.argmax. This can be done by taking the index and then doing some quick math with the shape of the array. Commented Jul 13, 2018 at 20:54

3 Answers 3

4

You can also use argmax with unravel_index:

def max_by_index(idx, arr):
    return (idx,) + np.unravel_index(np.argmax(arr[idx]), arr.shape[1:])

e.g.

import numpy as np
a = np.array([[[ 0.25,  0.10 ,  0.50 ,  0.15],
               [ 0.50,  0.60 ,  0.70 ,  0.30]],
              [[ 0.25,  0.50 ,  0.20 ,  0.70],
               [ 0.80,  0.10 ,  0.50 ,  0.15]]])

def max_by_index(idx, arr):
    return (idx,) + np.unravel_index(np.argmax(arr[idx]), arr.shape[1:])


print(max_by_index(0, a))

gives

(0, 1, 2)

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

1 Comment

damn too late, was just about to post this. With the same mistake you corrected in the edit ;)
2

You can use numpy.where, which you can wrap in a simple function to meet your requirements:

def max_by_index(idx, arr):
    return np.where(arr[idx] == np.max(arr[idx]))

In action:

>>> max_by_index(0, a)
(array([1], dtype=int64), array([2], dtype=int64))

You can index your array with this result to access the maximum value:

>>> a[0][max_by_index(0, a)]
array([0.7])

This will return all locations of the maximum value, if you only want a single occurrence, you may replace np.max with np.argmax.

1 Comment

Beware that np.where may not return anything at all when comparing float numbers with ==
0
col = (np.argmax(a[i])) % (a[i].shape[1])
row = (np.argmax(a[i])) // (a[i].shape[1])

This also helped

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.