I am trying to get the maximum of the first axis (of a 3d array), but get the maximum for only every 12th element.
Using a random 3D numpy array (that has the first axis divisible by 12), the first axis is a size of 36. and I want to get the maximum of the first 12 elements, then 12 - 24, and then 24 - 36.
I tried:
## 3d array
array = np.random.rand(36,20,30)
# get the maximum for every 12 units:
maximum_every_12 = np.zeros((int(array.shape[0]/12),array.shape[1],array.shape[2]))
for i in range(12):
maximum_every_12[i,:,:] = np.max(array[i::12,:,:],axis=0)
but I get an index error:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
/tmp/ipykernel_1643197/1714711606.py in <module>
8
9 for i in range(12):
---> 10 maximum_every_12[i,:,:] = np.max(array[i::12,:,:],axis=0)
IndexError: index 3 is out of bounds for axis 0 with size 3
How might I get the maximum value for every 12th element based on the first axis of the 3d array (size 36, 20, 30).
CodePudding user response:
You have the size of the arrays wrong. The first axis of maximum_every_12
is of length 36 / 12
which is 3. Therefore you cannot iterate over range(12)
, which fails at i = 4
. You must iterate over range(36/12)
.