This error message is because your array is designed to store integers:
>>> import numpy as np >>> a = np.arange(3) >>> a array([0, 1, 2]) >>> a.dtype dtype('int32') >>> a[0] = np.nan Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: cannot convert float NaN to integer
If your array is for floats, it will work. You can do this without loops:
>>> a = np.arange(3.0) >>> a array([ 0., 1., 2.]) >>> a[a==0] array([ 0.]) >>> a[a==0] = np.nan >>> a array([ nan, 1., 2.])
If you want to convert an array to a floating-point array, you can use astype :
>>> a = a.astype(float) >>> a array([ 0., 1., 2.]) >>> a.dtype dtype('float64')
source share