[Numpy-discussion] numpy.nansum() behavior in 1.3.0

josef.pktd at gmail.com josef.pktd at gmail.com
Mon Jun 1 14:34:49 EDT 2009


On Mon, Jun 1, 2009 at 2:26 PM, Keith Goodman <kwgoodman at gmail.com> wrote:
> On Mon, Jun 1, 2009 at 11:16 AM,  <josef.pktd at gmail.com> wrote:
>> On Mon, Jun 1, 2009 at 1:43 PM, Keith Goodman <kwgoodman at gmail.com> wrote:
>>> On Mon, Jun 1, 2009 at 9:55 AM, Michael Hearne <mhearne at usgs.gov> wrote:
>>>> A question (and possibly a bug):
>>>>
>>>> What should be returned when I do:
>>>>
>>>> numpy.nansum([])
>>>>
>>>> In my copy of numpy 1.1.1, I get 0.0.  This is what I would expect to
>>>> see.
>>>> However, this behavior seems to have changed in 1.3.0, in which I get
>>>> nan.
>>>
>>> Here's a weird one. This is in numpy 1.2:
>>>
>>>>> np.sum(9)
>>>   9
>>>>> np.sum(9.0)
>>>   9.0
>>>>> np.nansum(9)
>>>   9
>>>>> np.nansum(9.0)
>>> ---------------------------------------------------------------------------
>>> IndexError: 0-d arrays can't be indexed.
>>
>> wrong argument in isnan, I think
>>
>> Josef
>>
>> In file: C:\Programs\Python25\Lib\site-packages\numpy\lib\function_base.py
>>
>> def _nanop(op, fill, a, axis=None):
>>    """
>> ...
>>
>>    """
>>    y = array(a,subok=True)
>> -    mask = isnan(a)
>> +   mask = isnan(y)
>>    if mask.all():
>>        return np.nan
>>
>>    if not issubclass(y.dtype.type, np.integer):
>>        y[mask] = fill
>>
>>    return op(y, axis=axis)
>
> The problem I came across, np.nansum(float), is caused by this line
>
> y[mask] = fill
>
> when y is 0-d.

if mask is an array then this works, my initial solution was mask =
np.array(mask).  then I thought it works also the other way, but it
doesn't. I shouldn't have changed my mind

>>> y
array(9.0)
>>> y[np.array(np.isnan(9))] = 0
>>> y
array(9.0)
>>> y[np.isnan(np.array(9))] = 0
Traceback (most recent call last):
  File "<pyshell#45>", line 1, in <module>
    y[np.isnan(np.array(9))] = 0
IndexError: 0-d arrays can't be indexed.

Josef



More information about the NumPy-Discussion mailing list