Perform an operation on one specific dimension of an array

I am having a problem performing this operation on an n-dimensional array. Specifically, I have an array whose size is 5:

In [223]: data.ndim
Out[223]: 5

      

and with a form equal to:

In [224]: shape(data)
Out[224]: (6, 26, 27, 6, 50)

      

I would like to know if it is possible to perform an operation on the last dimension for the whole other dimension (for example max(data[0,0,0,0,:])

), but without using a for loop.

Hope I was clear enough! thanks for the help

+3


source to share


2 answers


out[i,j,k,l] = max(data[i,j,k,l,:])

can be written as one of the following

out = np.max(data, axis=-1)
out = np.max(data, axis=4)

      

It is often useful to keep size, but out2[i,j,k,l,0] = max(data[i,j,k,l,:])

. You can do this by passing:



out2 = np.max(data, axis=-1, keepdims=True)

      

So out2.shape == (6, 26, 27, 6, 1)

is handy because it now correctly passes messages to the input.

For more information, check out the arguments for ufunc.reduce

, which are sum

and max

are thin wrappers around

+6


source


Most functions in numpy accept a keyword argument for this axis

:

data.max(axis=4)

      



This will find the maximum on the 5th axis (they start at 0). The result will be in the form (6, 26, 27, 6)

.

+2


source







All Articles