Can you assign only unmasked values using numpy.ma?

Question:

Is there a way to copy values from one numpy masked array to another where ONLY the unmasked values are copied and the target values are left unchanged for masked source values? It seems like this should be handled automatically, but so far I haven’t found a good way to do it. Right now I’m using ma.choose with the target region of the destination and the mask, but it really seems like there should be a better way given that the entire purpose of the masked array is to not operate on masked values automatically.

Asked By: Justin Olbrantz

||

Answers:

import numpy as np
from numpy import ma
x = ma.array([1, 2, 3, 4], mask=[0, 1, 1, 0])
y = np.array([5, 6, 7, 8])

y[~x.mask] = x[~x.mask]

which gives for y:

array([1, 6, 7, 4])
Answered By: 9769953
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.