move_median off by 1?

17 views
Skip to first unread message

brentp

unread,
Jun 29, 2011, 4:32:16 PM6/29/11
to bottle-neck
Hi, with this code:


import numpy as np
import bottleneck as bn

a = np.arange(10)
print "\n".join(map(str, zip(a, bn.move_median(a, 3))))

I get this output:
(0, nan)
(1, nan)
(2, 1.0)
(3, 2.0)
(4, 3.0)
(5, 4.0)
(6, 5.0)
(7, 6.0)
(8, 7.0)
(9, 8.0)

It seems to me that the RHS should be [nan, 1 .. 8, nan]
instead of [nan, nan, 1..8]

am I missing something?
thanks,
-Brent

Brent Pedersen

unread,
Jun 29, 2011, 4:37:07 PM6/29/11
to bottle-neck

nevermind, the current behavior makes complete sense.
(as usual, it takes posting to a list for me to understand my mistake).

Keith Goodman

unread,
Jun 29, 2011, 4:41:18 PM6/29/11
to bottl...@googlegroups.com
On Wed, Jun 29, 2011 at 1:32 PM, brentp <bped...@gmail.com> wrote:
> Hi, with this code:
>
>
> import numpy as np
> import bottleneck as bn
>
> a = np.arange(10)
> print "\n".join(map(str, zip(a, bn.move_median(a, 3))))
>
> I get this output:
> (0, nan)
> (1, nan)
> (2, 1.0)
> (3, 2.0)
> (4, 3.0)
> (5, 4.0)
> (6, 5.0)
> (7, 6.0)
> (8, 7.0)
> (9, 8.0)
>
> It seems to me that the RHS should be [nan, 1 .. 8, nan]
> instead of [nan, nan, 1..8]

Looks like you'd like a centered moving median. The moving median in
bottleneck, however, puts the moving median in the position of the
last element in the window:

>> bn.move_median([0,1,2], 3)
array([ nan, nan, 1.])

BTW, how would a centered moving median work for an even window?

Keith Goodman

unread,
Jun 29, 2011, 4:43:26 PM6/29/11
to bottl...@googlegroups.com

I do that all the time. It works even better, BTW, when you post to a
large list like NumPy.

Brent Pedersen

unread,
Jun 29, 2011, 4:45:48 PM6/29/11
to bottl...@googlegroups.com

yes, i was looking for centered, came up with this:


def centered_median(a, window):
"""
centered moving median
"""
assert window % 2 != 0
w = (window - 1) / 2
t = bn.move_median(a, window)
t = np.roll(t, -w)
t[:w] = a[:w]
t[-w:] = a[-w:]
return t

Reply all
Reply to author
Forward
0 new messages