Home > Net >  Mean till i-ith element of an Array
Mean till i-ith element of an Array

Time:01-06

I need to calculate the mean of an array (length n) but only to the i-ith element (i<=n). For example an Array filled with dice rolls.

x = {1,4,5,3,6,...}

My current method is to use a loop and numpy.mean and slice the array each step:

x_mean_ith[0] = x[0]
for i in range(1,n):                                                
    x_mean_ith[i] = np.mean(x[:i])

This Method is too slow and i need it to be significantly faster. Currently it takes this part of the code ~ 2mins when the array is in the order of n = 10^6. Is there maybe a smarter way to calculate this without it taking to much time , memory usage is not important.

CodePudding user response:

You could do it using efficient (vectorized) cumulative sum:

x_mean_ith = np.cumsum(x) / np.arange(1,len(x) 1)
  •  Tags:  
  • Related