[Numpy-discussion] Difference between shape=() and shape=(1,)
Keith Goodman
kwgoodman at gmail.com
Tue Jul 13 13:06:26 EDT 2010
On Tue, Jul 13, 2010 at 9:54 AM, John Reid <j.reid at mail.cryst.bbk.ac.uk> wrote:
> Hi,
>
> I have some arrays of various shapes in which I need to set any NaNs to
> 0. I have been doing the following:
>
> a[numpy.where(numpy.isnan(a)] = 0.
>
> as you can see here:
>
> In [20]: a=numpy.ones(2)
>
> In [21]: a[1]=numpy.log(-1)
>
> In [22]: a
> Out[22]: array([ 1., NaN])
>
> In [23]: a[numpy.where(numpy.isnan(a))]=0.
>
> In [24]: a
> Out[24]: array([ 1., 0.])
>
> Unfortunately, I've just discovered that when a.shape == () this doesn't
> work at all. For example:
>
> In [41]: a=numpy.array((1.))
>
> In [42]: a.shape
> Out[42]: ()
>
> In [43]: a[numpy.where(numpy.isnan(a))]=0.
>
> In [44]: a
> Out[44]: array(0.0)
No need to use where. You can just do a[np.isnan(a)] = 0. But you do
have to watch out for 0d arrays, can't index into those. How about:
>> def nan_replace(a, fill=0):
....: a = a.copy()
....: if a.ndim == 0:
....: return a
....: a[np.isnan(a)] = fill
....: return a
....:
>>
>> a = np.array(9)
>> nan_replace(a, 0)
array(9)
>> a = np.array([9, np.nan])
>> nan_replace(a, 0)
array([ 9., 0.])
Oh, I guess a[np.isnan(a)] = fill makes a copy so the a.copy() can be
moved inside the if statement.
More information about the NumPy-Discussion
mailing list