[Numpy-discussion] nan_to_num and bool arrays
Keith Goodman
kwgoodman at gmail.com
Fri Dec 11 15:41:02 EST 2009
On Fri, Dec 11, 2009 at 12:08 PM, Bruce Southey <bsouthey at gmail.com> wrote:
> On 12/11/2009 01:33 PM, Robert Kern wrote:
>> On Fri, Dec 11, 2009 at 13:11, Bruce Southey<bsouthey at gmail.com> wrote:
>>
>>
>>> As documented, nan_to_num returns a float so it does not return the
>>> input unchanged.
>>>
> Sorry for my mistake:
> Given an int input, np.nan_to_num returns an int dtype
> >>> np.nan_to_num(np.zeros((3,3), dtype=np.int)).dtype
> dtype('int64')
>
>> 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.
>>
>
> So I agree that it should leave the input untouched when a non-float
> dtype is used for some array-like input.
Would only one line need to be changed? Would changing
if not issubclass(t, _nx.integer):
to
if not issubclass(t, _nx.integer) and not issubclass(t, _nx.bool_):
do the trick?
Here's nan_to_num for reference:
def nan_to_num(x):
try:
t = x.dtype.type
except AttributeError:
t = obj2sctype(type(x))
if issubclass(t, _nx.complexfloating):
return nan_to_num(x.real) + 1j * nan_to_num(x.imag)
else:
try:
y = x.copy()
except AttributeError:
y = array(x)
if not issubclass(t, _nx.integer):
if not y.shape:
y = array([x])
scalar = True
else:
scalar = False
are_inf = isposinf(y)
are_neg_inf = isneginf(y)
are_nan = isnan(y)
maxf, minf = _getmaxmin(y.dtype.type)
y[are_nan] = 0
y[are_inf] = maxf
y[are_neg_inf] = minf
if scalar:
y = y[0]
return y
More information about the NumPy-Discussion
mailing list