2

Suppose i have given a numpy array like this:

a = np.array([1, 2, 3, 4, np.nan, 5, np.nan, 6, np.nan])
# [1, 2, 3, 4, nan, 5, nan, 6, nan]

I know the number of nan values in the array and have the according array for replacement, e.g.:

b = np.array([12, 13, 14])
# [12, 13, 14]

What is the pythonic way of substituting the array b for all the nan value, such that I get the reult:

[1, 2, 3, 4, 12, 5, 13, 6, 14]

1 Answer 1

6

Perform boolean indexing on a using np.isnan and replace with b as:

a[np.isnan(a)] = b

print(a)
# array([ 1.,  2.,  3.,  4., 12.,  5., 13.,  6., 14.])
Sign up to request clarification or add additional context in comments.

1 Comment

I'll just add this as a reference docs.scipy.org/doc/numpy/user/misc.html to emphasize that np.isnan is probably the way to do it, as np.nan == np.nan is always False.

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.