[Numpy-discussion] nan_to_num and bool arrays

Robert Kern robert.kern@gmail....
Fri Dec 11 13:33:07 CST 2009

On Fri, Dec 11, 2009 at 13:11, Bruce Southey <bsouthey@gmail.com> wrote:

> As documented, nan_to_num returns a float so it does not return the
> input unchanged.

I think that is describing the current behavior rather than
documenting the intent of the function. Given the high level purpose
of the function, to "[r]eplace nan with zero and inf with finite
numbers," I think it is fairly reasonable to implement it as a no-op
for integers and related dtypes. There are no nans or infs for those
dtypes so the input can be passed back 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

No, that's the other way around, converting floats to bools.
Converting bools to floats is trivial: True->1.0, False->0.0.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco

More information about the NumPy-Discussion mailing list