Reduce array size by averaging contiguous values ​​with numpy

I have a large array of thousands of vals in numpy. I want to reduce its size by averaging adjacent values. For example:

a = [2,3,4,8,9,10]
#average down to 2 values here
a = [3,9]
#it averaged 2,3,4 and 8,9,10 together

      

So basically, I have n number of elements in an array, and I want to tell it to average up to X number of values, and it averages as above.

Is there a way to do this with numpy (already using it for other things, so I would like to stick with it).

+3


source to share


3 answers


As mentioned in the comments, you probably want:



group = 3
a = a.reshape(-1, group).mean(axis=1)

      

+5


source


Looks like a simple non-overlapping moving window, average to me, how about:



In [3]:

import numpy as np
a = np.array([2,3,4,8,9,10])
window_sz = 3
a[:len(a)/window_sz*window_sz].reshape(-1,window_sz).mean(1) 
#you want to be sure your array can be reshaped properly, so the [:len(a)/window_sz*window_sz] part
Out[3]:
array([ 3.,  9.])

      

0


source


Try the following:

n_averaged_elements = 3
averaged_array = []
a = np.array([ 2,  3,  4,  8,  9, 10])
for i in range(0, len(a), n_averaged_elements):
   slice_from_index = i
   slice_to_index = slice_from_index + n_averaged_elements
   averaged_array.append(np.mean(a[slice_from_index:slice_to_index]))

>>>> averaged_array
>>>> [3.0, 9.0]

      

0


source







All Articles