Search code examples
pythonarraysnumpymeanelementwise-operations

Numpy - Calculate element wise mean for a 1D array


I found multible questions with similar titles but they didn't match with my case.

I have a np.array with offset values and I want the mean value for index from all previous values.

My first approach was with a for loop, but with huge arrays it is obviously way to slow.

offset = np.array([2, 4, 5, 7, 8, 10])
mean_mraw = []

for i, ofs in enumerate(offset):
        mean_mraw.append(offset[0:i+1].mean())

So what I expect is this:

mean_mraw = [2, 3, 3.6, 4.5, 5.2, 6] #np.array

Is there np- build in function for that or how could I solve that in another way.

Thanks


Solution

  • You can use the cumulated sum (np.cumsum) and divide by the number of seen elements (using np.arange):

    a = np.array([2, 4, 5, 7, 8, 10])
    out = np.cumsum(a)/(np.arange(a.shape[0])+1)
    

    output:

    array([2.        , 3.        , 3.66666667, 4.5       , 5.2       ,
           6.        ])