3

if have an array of shape (9,1,3).

array([[[  6,  12, 108]],

   [[122, 112,  38]],

   [[ 57, 101,  62]],

   [[119,  76, 177]],

   [[ 46,  62,   2]],

   [[127,  61, 155]],

   [[  5,   6, 151]],

   [[  5,   8, 185]],

   [[109, 167,  33]]])

I want to find the argmax index of the third dimension, in this case it would be 185, so index 7.

I guess the solution is linked to reshaping but I can't wrap my head around it. Thanks for any help!

  • 1
    Sounds more like you want `np.argmax(yourarray[:, 0, 2])`. – Paul Panzer Jan 20 '18 at 19:25
  • 1
    It doesn't really make much sense to say "the argmax index of the third dimension". You could ask for the third coordinate of the argmax (which would be 2, not 7) or the first coordinate, which would be 7, or the argmax of the sliced array after taking [:, 0, 2] (as PP suggested, which is indeed 7). – DSM Jan 20 '18 at 19:30
  • I don't get why every item is a singleton list, seems like a bad modeling. – Willem Van Onsem Jan 20 '18 at 19:41
  • @PaulPanzer how about `np.argmax(np.max(arr, 2))` ? – kmario23 Jan 20 '18 at 19:48
  • @kmario23 or `np.unravel_index(np.argmax(arr), arr.shape)`? Anything that results in something with a seven in it. – Paul Panzer Jan 20 '18 at 20:06

2 Answers2

2

I'm not sure what's tricky about it. But, one way to get the index of the greatest element along the last axis would be by using np.max and np.argmax like:

# find `max` element along last axis 
# and get the index using `argmax` where `arr` is your array
In [53]: np.argmax(np.max(arr, axis=2))
Out[53]: 7

Alternatively, as @PaulPanzer suggested in his comments, you could use:

In [63]: np.unravel_index(np.argmax(arr), arr.shape)
Out[63]: (7, 0, 2)

In [64]: arr[(7, 0, 2)]
Out[64]: 185
kmario23
  • 57,311
  • 13
  • 161
  • 150
1

You may have to do it like this:

data = np.array([[[  6,  12, 108]],

   [[122, 112,  38]],

   [[ 57, 101,  62]],

   [[119,  76, 177]],

   [[ 46,  62,   2]],

   [[127,  61, 155]],

   [[  5,   6, 151]],

   [[  5,   8, 185]],

   [[109, 167,  33]]])

np.argmax(data[:,0][:,2])
 7
Xenolion
  • 12,035
  • 7
  • 33
  • 48
jrjames83
  • 901
  • 2
  • 9
  • 22