0

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?

3
  • It is not very clear what you mean by "I don't keep the same dimension". So, for the (9, 2, 3) array test, do you want a (9, 2, 3) array as a result, a (2, 2, 3) array, or something else? We could help you best if you could explicitly add the correct result for test_mean for reference. Commented Jul 21, 2014 at 11:24
  • It is also a good idea to stay online for a while after posting a question. Otherwise potential answerers might move on if they can't get you to comment on requests for clarification. Commented Jul 21, 2014 at 11:28
  • As i would say, i would like to keep the (9, 2, 3) array! Thanks ;) (& i had to go). Commented Jul 21, 2014 at 11:31

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.