2

I have 2 arrays:

import numpy as np
A = np.array([[np.nan,np.nan,0],[4,5,6],[7,8,9]])
B = np.zeros((len(A),len(A[0])))

For every NaN in A, I would like to replace the zero in B at the corresponding indices by np.nan. How can I do that ? I tried with masks but couldn't make it work.

B = np.ma.masked_where(np.isnan(A) == True, np.nan) 

In reality I am working with bigger arrays (582x533) so I don't want to do it by hand.

0

2 Answers 2

3

You can use np.isnan(A) directly:

B = np.zeros_like(A)
B[np.isnan(A)] = np.nan

np.where is useful for when you want to construct B directly:

B = np.where(np.isnan(A), np.nan, 0)
Sign up to request clarification or add additional context in comments.

1 Comment

@user1740577. Your answer is fine, but you sort of conflated two approaches that are simpler by themselves. I appreciate the endorsement.
2

You can create np.zeros with A.shape then use np.where like below:

(this approach construct B two times)

>>> import numpy as np
>>> A = np.array([[np.nan,np.nan,0],[4,5,6],[7,8,9]])
>>> B = np.zeros(A.shape)
>>> B = np.where(np.isnan(A) , np.nan, B)
>>> B
array([[nan, nan,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

2 Comments

You really don't need to recreate B a second time
@MadPhysicist OK, Understand ;)

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.