2964502
2964502

Reputation: 4479

convert np.nan into value in numpy array

import numpy as np

a = np.array([1,2,3,4,5,6,7,8,9])
b = np.where (a==3,np.nan,a)
print (b) #OK, can convert certain values (e.g. 3) into np.nan

c = np.where (b==np.nan,3,b)

print (c)

But does not work! Could not convert np.nan into 3. How can I convert np.nan in the array c into the value 3? The result (array c) should be same as the original array a.

Upvotes: 0

Views: 3822

Answers (2)

M4rtini
M4rtini

Reputation: 13539

c = np.where(np.isnan(b), 3, b)

Upvotes: 5

DSM
DSM

Reputation: 352989

Working with nan is a little tricky because nan != nan. You could use np.isnan and boolean indexing, though:

>>> a = np.arange(10.0)
>>> a
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])
>>> a[a % 3 == 0] = np.nan
>>> a
array([ nan,   1.,   2.,  nan,   4.,   5.,  nan,   7.,   8.,  nan])
>>> a[np.isnan(a)] = 999
>>> a
array([ 999.,    1.,    2.,  999.,    4.,    5.,  999.,    7.,    8.,  999.])

Upvotes: 3

Related Questions