I wrote a python script below:
import numpy as np
arr = np.arange(6).reshape(2, 3)
arr[arr==0]=['nan']
print arr
But I got this error:
Traceback (most recent call last):
File "C:\Users\Desktop\test.py", line 4, in <module>
arr[arr==0]=['nan']
ValueError: invalid literal for long() with base 10: 'nan'
[Finished in 0.2s with exit code 1]
How to replace zeros in a NumPy array with nan?
Best Answer
np.nan
has typefloat
: arrays containing it must also have this datatype (or thecomplex
orobject
datatype) so you may need to castarr
before you try to assign this value.The error arises because the string value
'nan'
can't be converted to an integer type to matcharr
's type.