0
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.

2 Answers 2

5
c = np.where(np.isnan(b), 3, b)
Sign up to request clarification or add additional context in comments.

Comments

3

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.])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.