I have an array 1200*1200. Some of its values are zero. I want to convert the zero values to numpy.nan values. This is my solution:
import numpy
for i in range(1200):
for j in range(1200):
if data_a[i, j] == 0:
data_a[i, j] = numpy.nan
But I got this error: data_a[i,j] = numpy.nan
ValueError: cannot convert float NaN to integer
I don't understand the error. Any alternatives or solutions?
That error message is because your array is for storing 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, though, it'll work. You can do it without loops, too:
>>> 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 your array to a float array, you could use astype
:
>>> a = a.astype(float)
>>> a
array([ 0., 1., 2.])
>>> a.dtype
dtype('float64')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With