Q:

Python - Average values of numpy multidimensionnal array every specific time

I have a multidimensionnal array "test[:,:,:]" and i would like to get averaged values on the test.shape[0] dimension for every 4 "frames" i would like to keep the same dimensions of my array and substitute the 4 values by the mean value.
As example:
test=np.array([[[ 2.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 3.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 3.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 5.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 2.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 3.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 3.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 5.,  1.,  1.],
        [ 1.,  1.,  1.]],

       [[ 2.,  1.,  1.],
        [ 1.,  1.,  1.]]])        

for i in range(test.shape[0]-1,4):
    test_mean = (test[i,:,:]+test[i+1,:,:]+test[i+2,:,:]+test[i+3,:,:])/4.

But, i don't keep the same dimension...what is the best way to do that?

A:

You are overwriting test_mean every time. A good start is:
test_mean = np.zeros_like(test)
for i in xrange(test.shape[0]-4):
    test_mean[i] = test[i:i+4].mean(axis=0)

Here is a more efficient implementation from scipy:
from scipy.ndimage import uniform_filter1d
test_mean2 = uniform_filter1d(test, 4, axis=0)

Check the documentation to understand how the result is stored and what options you have to treat boundary values.

