Zero values ​​of the array to be converted to nan values

I have an array of 1200 * 1200. Some of its values ​​are zero. I want to convert null values ​​to numpy.nan values. This is my decision:

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 do not understand the error. Any alternatives or solutions?

+4
source share
1 answer

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') 
+6
source

Source: https://habr.com/ru/post/1444970/


All Articles