Rectangle 27 0

python Replace zeros in a numpy array with nan?


>>> arr = arr.astype('float')
>>> arr[arr == 0] = 'nan' # or use np.nan
>>> arr
array([[ nan,   1.,   2.],
       [  3.,   4.,   5.]])

The string 'nan' is interpreted as np.nan if you have a float array:

np.nan has type float: arrays containing it must also have this datatype (or the object datatype) so you may need to recast arr before you try to assign the value. The error arises because the string value 'nan' can't be converted to an integer type to match arr's type.

Note