Replace the zeros in a NumPy integer array with nan
np.nan
has type float
: arrays containing it must also have this datatype (or the complex
or object
datatype) so you may need to cast arr
before you try to assign this value.
The error arises because the string value 'nan'
can't be converted to an integer type to match arr
's type.
>>> arr = arr.astype('float')>>> arr[arr == 0] = 'nan' # or use np.nan>>> arrarray([[ nan, 1., 2.], [ 3., 4., 5.]])