[Numpy-discussion] nan_to_num and bool arrays
Bruce Southey
bsouthey at gmail.com
Fri Dec 11 14:11:41 EST 2009
On 12/11/2009 10:21 AM, Keith Goodman wrote:
> On Fri, Dec 11, 2009 at 12:50 AM, Nicolas Rougier
> <Nicolas.Rougier at loria.fr> wrote:
>
>> Hello,
>>
>> Using both numpy 1.3.0 and 1.4.0rc1 I got the following exception using
>> nan_to_num on a bool array, is that the expected behavior ?
>>
>>
>>
>>>>> import numpy
>>>>> Z = numpy.zeros((3,3),dtype=bool)
>>>>> numpy.nan_to_num(Z)
>>>>>
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in<module>
>> File "/usr/lib/python2.6/dist-packages/numpy/lib/type_check.py", line
>> 374, in nan_to_num
>> maxf, minf = _getmaxmin(y.dtype.type)
>> File "/usr/lib/python2.6/dist-packages/numpy/lib/type_check.py", line
>> 307, in _getmaxmin
>> f = getlimits.finfo(t)
>> File "/usr/lib/python2.6/dist-packages/numpy/core/getlimits.py", line
>> 103, in __new__
>> raise ValueError, "data type %r not inexact" % (dtype)
>> ValueError: data type<type 'numpy.bool_'> not inexact
>>
> I guess a check for bool could be added at the top of nan_to_num. If
> the input x is a bool then nan_to_num would just return x unchanged.
> Or perhaps
>
> maxf, minf = _getmaxmin(y.dtype.type)
>
> could return False, True.
>
> Best bet is probably to file a ticket. And then pray.
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
As documented, nan_to_num returns a float so it does not return the
input unchanged.
That is the output of np.nan_to_num(np.zeros((3,3))) is a float array
not an int array. This is also why np.finfo() fails because it is not
give a float (that is, it also gives the same output if the argument to
np.finfo() is an int rather than an boolean type).
I am curious why do you expect this conversion to work given how Python
defines boolean types
(http://docs.python.org/library/stdtypes.html#boolean-values).
It is ambiguous to convert from boolean to float since anything that is
not zero is 'True' and that NaN is not zero:
>>> bool(np.PINF)
True
>>> bool(np.NINF)
True
>>> bool(np.NaN)
True
>>> bool(np.PZERO)
False
>>> bool(np.NZERO)
False
So what do you behavior do you expect to see?
Bruce
More information about the NumPy-Discussion
mailing list