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)
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-.