0

I have two numpy.ndarray and i found a not elegant solution (using more than 4 lines code) to mask the data2 with data1. I am asking an elegant solution, saving line to do:

example.

data1 = np.array([[1,2,np.nan,4,5],[np.nan,7,np.nan,9,np.nan],[11,12,13,14,np.nan],[np.nan,17,np.nan,19,20]])
data2 = np.ones((6, 4))

print data1
[[  1.   2.  nan   4.   5.]
 [ nan   7.  nan   9.  nan]
 [ 11.  12.  13.  14.  nan]
 [ nan  17.  nan  19.  20.]]
>>> print data2
[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

the result i wish to have is:

[[  1.   2.  1   4.   5.]
 [ 1   7.  1   9.  1]
 [ 11.  12.  13.  14.  1]
 [ 1  17.  1  19.  20.]]

in other words, where data1 is nan the value of data2

Thanks in advance for help and suggestions. I did this with more than 4 lines of code

1 Answer 1

2

Assuming you mean to have data1 and data2 as arrays of the same size (which would change your example to read):

data2 = np.ones((4, 5))

A one line approach is:

data1[np.isnan(data1)] = data2[np.isnan(data1)]
Sign up to request clarification or add additional context in comments.

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.