I have a 2D numpy array. Some of the values in this array are NaN
. I want to perform certain operations using this array. For example consider the array:
nan is never equal to nan
if z!=z:z=0
so for a 2D array
for entry in nparr:
if entry!=entry:entry=0
Where A
is your 2D array:
import numpy as np
A[np.isnan(A)] = 0
The function isnan
produces a bool array indicating where the NaN
values are. A boolean array can by used to index an array of the same shape. Think of it like a mask.
For your purposes, if all the items are stored as str
and you just use sorted as you are using and then check for the first element and replace it with '0'
>>> l1 = ['88','NaN','67','89','81']
>>> n = sorted(l1,reverse=True)
['NaN', '89', '88', '81', '67']
>>> import math
>>> if math.isnan(float(n[0])):
... n[0] = '0'
...
>>> n
['0', '89', '88', '81', '67']
How about nan_to_num()?
A code example for drake's answer to use nan_to_num:
>>> import numpy as np
>>> A = np.array([[1, 2, 3], [0, 3, np.NaN]])
>>> A = np.nan_to_num(A)
>>> A
array([[ 1., 2., 3.],
[ 0., 3., 0.]])
This should work:
from numpy import *
a = array([[1, 2, 3], [0, 3, NaN]])
where_are_NaNs = isnan(a)
a[where_are_NaNs] = 0
In the above case where_are_NaNs is:
In [12]: where_are_NaNs
Out[12]:
array([[False, False, False],
[False, False, True]], dtype=bool)