I have a 3D numpy of shape (900,10,54).
And I want to average the values of every two elements into one, for axis 1.
Expected outcome would have shape: (900,5,54).
I have a 3D numpy of shape (900,10,54).
And I want to average the values of every two elements into one, for axis 1.
Expected outcome would have shape: (900,5,54).
One way to do this:
This uses numpy array slicing to achieve this.
import numpy as np
x = np.random.rand(900, 10, 64)
y = (x[:, ::2, :] + x[:, 1::2, :]) / 2
Another approach:
If you have a variable number of consecutive elements in axis = 1 that you want to sum (which was 2 above), you can use reshape and mean to achieve this.
n = 2
y = x.reshape(x.shape[0], x.shape[1] // n, n, x.shape[2]) # shape = (900, 5, 2, 64)
y = y.mean(axis = 2)
This sums consecutive n rows for each of inner matrices in your 3D array x.