[SciPy-User] scipy.stats.nanmedian
Keith Goodman
kwgoodman at gmail.com
Thu Jan 21 20:54:28 EST 2010
I noticed a couple of issues with nanmedian in scipy.stats:
>> from scipy.stats import nanmedian
>> nanmedian(1)
---------------------------------------------------------------------------
ValueError: axis must be less than arr.ndim; axis=0, rank=0.
>> nanmedian(True)
---------------------------------------------------------------------------
ValueError: axis must be less than arr.ndim; axis=0, rank=0.
>> nanmedian(np.array(1))
---------------------------------------------------------------------------
ValueError: axis must be less than arr.ndim; axis=0, rank=0.
>> nanmedian(np.array([1, 2, 3]))
array(2.0)
Changing the function from the original:
def nanmedian(x, axis=0):
x, axis = _chk_asarray(x,axis)
x = x.copy()
return np.apply_along_axis(_nanmedian,axis,x)
to this (I know, it is not pretty):
def nanmedian(x, axis=0):
if np.isscalar(x):
return float(x)
x, axis = _chk_asarray(x, axis)
if x.ndim == 0:
return float(x.tolist())
x = x.copy()
x = np.apply_along_axis(_nanmedian, axis, x)
if x.ndim == 0:
x = float(x.tolist())
return x
gives the expected results:
>> nanmedian(1)
1.0
>> nanmedian(True)
1.0
>> nanmedian(np.array(1))
1.0
>> nanmedian(np.array([1, 2, 3]))
2.0
which agree with numpy:
>> np.median(1)
1.0
>> np.median(True)
1.0
>> np.median(np.array(1))
1.0
>> np.median(np.array([1, 2, 3]))
2.0
I'm keeping a local copy of the changes I made for my own package. But
it would be nice (for me) if this was fixed upstream. Are the changes
above good enough for scipy?
(Another difference from np.median that I noticed is that the default
axis for np.median is None and for scipy.stats.nanmean it is 0. But
perhaps it is too late to change that.)
More information about the SciPy-User
mailing list