Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

zero values of an array to be converted to nan values

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?

like image 678
f.ashouri Avatar asked Feb 18 '23 13:02

f.ashouri


1 Answers

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')
like image 74
DSM Avatar answered Feb 21 '23 03:02

DSM