# [Numpy-discussion] A faster median (Wirth's method)

John Salvatier jsalvati at u.washington.edu
Wed Dec 1 11:07:18 EST 2010

```@Keith Goodman

I think I figured it out. I believe something like the following will do
what you want, iterating across one axis specially, so it can apply a median
function along an axis. This code in particular is for calculating a moving
average and seems to work (though I haven't checked my math). Let me know if
you find any problems.

def ewma(a, d,  int axis = -1):

out = np.empty(a.shape, dtype)

cdef np.flatiter ita, ito

ita = np.PyArray_IterAllButAxis(a,   &axis)
ito = np.PyArray_IterAllButAxis(out, &axis)

cdef int i
cdef int axis_length = a.shape[axis]
cdef int a_axis_stride = a.strides[axis]/a.itemsize
cdef int o_axis_stride = out.strides[axis]/out.itemsize

cdef double avg = 0.0
cdef double weight = 1.0 - np.exp(-d)

while np.PyArray_ITER_NOTDONE(ita):

avg = 0.0
for i in range(axis_length):

avg += (<dtype_t*>np.PyArray_ITER_DATA (ita))[i * a_axis_stride
] * weight + avg * (1 - weight)
(<dtype_t*>np.PyArray_ITER_DATA (ito))[i * o_axis_stride ] = avg

np.PyArray_ITER_NEXT(ita)
np.PyArray_ITER_NEXT(ito)

return out

On Tue, Nov 30, 2010 at 9:46 PM, Felix Schlesinger <schlesin at cshl.edu>wrote:

> > > import numpy as np
> > > cimport numpy as cnp
> >
> > > cdef cnp.float64_t namean(cnp.ndarray[cnp.float64_t, ndim=1] a):
> > >    return np.nanmean(a)  # just a placeholder
> >
> > > is not allowed?  It works for me.  Is it a cython version thing?
> > > (I've got 0.13),
> >
> > Oh, that's nice! I'm using 0.11.2. OK, time to upgrade.
>
> Oh wow, does that mean that http://trac.cython.org/cython_trac/ticket/177
> is fixed? I couldn't find anything in the release notes about that,
> but it would be great news. Does the cdef function acquire and hold
> the buffer?
>
> Felix
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20101201/6b90efc9/attachment.html>
```