Reputation: 697
I have a two-dimensional numpy-array. It has a shape of (6994, 6994)
. There are many values of -1000
which I would like to encode as NAN
. I tried:
array[array == -1000] = np.NAN
, but this gives me the error cannot convert float NaN to integer
When I tried to write a function:
def valtona(array, val):
for i in array:
for j in array:
if array[i,j] == -1000:
array[i,j] = np.NAN
I get:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
I know there are some questions out there regarding the same issue, but I still didn't manage to fix it.
Upvotes: 2
Views: 3318
Reputation: 1373
You can use np.isclose() and set parameters to meet your needs to overcome the precision challenge of working with floats.
>>> a
array([ 0., 1., 2., 4., 4., 5., 6., 7., 8., 9.])
>>> a[3]
4.0000000000001004
>>> a[4]
4.0
>>> np.isclose(a,[4.0], .00000001, .00000001)
array([False, False, False, True, True, False, False, False, False, False], dtype=bool)
>>> np.isclose(a,[4.0])
array([False, False, False, True, True, False, False, False, False, False], dtype=bool)
>>> a[np.isclose(a,[4.0], .00000001, .00000001)]=np.nan
>>> a
array([ 0., 1., 2., nan, nan, 5., 6., 7., 8., 9.])
Upvotes: 1
Reputation: 3503
You can still use
array[array == -1000] = np.NAN
You just need to convert it to float
first.
array=array.astype('float')
array[array == -1000] = np.NAN
Upvotes: 4