[Numpy-discussion] nan_to_num and bool arrays

Keith Goodman kwgoodman at gmail.com
Fri Dec 11 23:27:50 EST 2009


On Fri, Dec 11, 2009 at 6:38 PM, Robert Kern <robert.kern at gmail.com> wrote:
> On Fri, Dec 11, 2009 at 18:38, Keith Goodman <kwgoodman at gmail.com> wrote:
>
>> That seems to work. To avoid changing the input
>>
>>>> x = np.array(1)
>>>> x.shape
>>   ()
>>>> y = nan_to_num(x)
>>>> x.shape
>>   (1,)
>>
>> I moved y = x.copy() further up and switched x's to y's. Here's what
>> it looks like:
>>
>> def nan_to_num(x):
>>    is_scalar = False
>>    if not isinstance(x, _nx.ndarray):
>>       x = asarray(x)
>>       if x.shape == ():
>>           # Must return this as a scalar later.
>>           is_scalar = True
>>    y = x.copy()
>>    old_shape = y.shape
>>    if y.shape == ():
>>       # We need element access.
>>       y.shape = (1,)
>>    t = y.dtype.type
>>    if issubclass(t, _nx.complexfloating):
>>        return nan_to_num(y.real) + 1j * nan_to_num(y.imag)
>
> Almost! You need to handle the shape restoration in this branch, too.
>
> In [9]: nan_to_num(array(1+1j))
> Out[9]: array([ 1.+1.j])

Taking care of my imaginary bug has the nice side effect of leaving us
with only one return statement. I changed

return nan_to_num(y.real) + 1j * nan_to_num(y.imag)

to

y = nan_to_num(y.real) + 1j * nan_to_num(y.imag)

And changed the if on the next line to elif.

def nan_to_num(x):
    is_scalar = False
    if not isinstance(x, _nx.ndarray):
       x = asarray(x)
       if x.shape == ():
           # Must return this as a scalar later.
           is_scalar = True
    y = x.copy()
    old_shape = y.shape
    if y.shape == ():
       # We need element access.
       y.shape = (1,)
    t = y.dtype.type
    if issubclass(t, _nx.complexfloating):
        y = nan_to_num(y.real) + 1j * nan_to_num(y.imag)
    elif issubclass(t, _nx.inexact):
        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 is_scalar:
        y = y[0]
    else:
        y.shape = old_shape
    return y



More information about the NumPy-Discussion mailing list