Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mean till i-ith element of an Array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

x_mean_ith = np.cumsum(x) / np.arange(1,len(x)+1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading