Numpy 3d to 2d based on 2d mask array

If I have ndarray:

>>> a = np.arange(27).reshape(3,3,3)
>>> a
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])

I know that I can get the maximum along a certain axis using np.max(axis=...):

>>> a.max(axis=2)
array([[ 2,  5,  8],
       [11, 14, 17],
       [20, 23, 26]])

Alternatively, I could get indexes along this axis that correspond to the maximum values ​​from:

>>> indices = a.argmax(axis=2)
>>> indices
array([[2, 2, 2],
       [2, 2, 2],
       [2, 2, 2]])

My question is. Given an array indicesand an array a, is there an elegant way to reproduce the array returned by the array a.max(axis=2)?

Maybe this will work:

import itertools as it
import numpy as np
def apply_mask(field,indices):
    data = np.empty(indices.shape)

    #It seems highly likely that there is a more numpy-approved way to do this.
    idx = [range(i) for i in indices.shape]
    for idx_tup,zidx in zip(it.product(*idx),indices.flat):
        data[idx_tup] = field[idx_tup+(zidx,)]
    return data

But it seems pretty hacked / ineffective. It also prevents me from using this with any axis other than the "last" axis. Is there a numpy function (or some use of numpy magic indexing) to make this work? Naive a[:,:,a.argmax(axis=2)]does not work.

UPDATE

, ( ):

import numpy as np
def apply_mask(field,indices):
    data = np.empty(indices.shape)

    for idx_tup,zidx in np.ndenumerate(indices):
        data[idx_tup] = field[idx_tup+(zidx,)]

    return data

, 1 ( argmax(axis=...)) ( ) . (, ). , "", "" . , 2d "" 3D-.

+4
2

numpy, , , , , .

def apply_mask(a, indices, axis):
    magic_index = [np.arange(i) for i in indices.shape]
    magic_index = np.ix_(*magic_index)
    magic_index = magic_index[:axis] + (indices,) + magic_index[axis:]
    return a[magic_index]

:

def apply_mask(a, indices, axis):
    magic_index = np.ogrid[tuple(slice(i) for i in indices.shape)]
    magic_index.insert(axis, indices)
    return a[magic_index]
+2

index_at() :

import numpy as np

def index_at(idx, shape, axis=-1):
    if axis<0:
        axis += len(shape)
    shape = shape[:axis] + shape[axis+1:]
    index = list(np.ix_(*[np.arange(n) for n in shape]))
    index.insert(axis, idx)
    return tuple(index)

a = np.random.randint(0, 10, (3, 4, 5))

axis = 1
idx = np.argmax(a, axis=axis)
print a[index_at(idx, a.shape, axis=axis)]
print np.max(a, axis=axis)
-1

All Articles