[Numpy-discussion] Mean of n values within an array

David Grant davidgrant at gmail.com
Sat Jul 29 17:37:23 CDT 2006

On 7/29/06, Charles R Harris <charlesr.harris at gmail.com> wrote:
> Hmmm,
> I rewrote the subroutine a bit.
> def numpy_nmean(list,n):
>     a = numpy.empty(len(list),dtype=float)
>     b = numpy.cumsum(list)
>     for i in range(0,len(list)):
>         if i < n :
>             a[i] = b[i]/(i+1)
>         else :
>             a[i] = (b[i] - b[i-n])/(i+1)
>     return a
> and got
> regular python took: 0.750000 sec.
> numpy took: 0.380000 sec.

I got rid of the for loop entirely. Usually this is the thing to do, at
least this will always give speedups in Matlab and also in my limited
experience with Numpy/Numeric:

def numpy_nmean2(list,n):
    a = numpy.empty(len(list),dtype=float)
    b = numpy.cumsum(list)
    c = concatenate((b[n:],b[:n]))
    a[:n] = b[:n]/(i+1)
    a[n:] = (b[n:] - c[n:])/(i+1)
    return a

I got no noticeable speedup from doing this which I thought was pretty
amazing. I even profiled all the functions, the original, the one written by
Charles, and mine, using hotspot just to make sure nothing funny was going
on. I guess plain old Python can be better than you'd expect in certain

David Grant
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20060729/694ede51/attachment-0001.html 

More information about the Numpy-discussion mailing list