[SciPy-User] nanmedian chokes on size zero arrays

Keith Goodman kwgoodman@gmail....
Wed Mar 2 15:06:37 CST 2011


On Wed, Mar 2, 2011 at 12:27 PM, Keith Goodman <kwgoodman@gmail.com> wrote:
> While fixing Bottleneck functions that can't handle size zero arrays
> of various shapes, I noticed that scipy.stats.nanmedian chokes on
> certain size zero arrays and axis combinations:
>
>>> from scipy.stats import nanmedian
>>> a = np.ones((0,2))
>>> np.median(a, 1)
>   array([], dtype=float64)
>>> nanmedian(a, 1)
> <snip>
> IndexError: invalid index
>
> Anyone know a fix? Here's the ticket:
> http://projects.scipy.org/scipy/ticket/1400

I guess the bug is in np.apply_along_axis:

>> np.apply_along_axis(np.sum, 1, np.ones((0,2)))
<snip>
IndexError: invalid index

But for my use I need a fix in my local copy of scipy.stats.nanmedian,
so I'll try something like this:

    x, axis = _chk_asarray(x, axis)
    if x.ndim == 0:
        return float(x.item())
    shape = list(x.shape)
    shape.pop(axis)
    if 0 in shape:
        x = np.empty(shape)
    else:
        x = x.copy()
        x = np.apply_along_axis(_nanmedian, axis, x)
        if x.ndim == 0:
            x = float(x.item())
    return x


More information about the SciPy-User mailing list