Home > Software design >  Can you assign only unmasked values using numpy.ma?
Can you assign only unmasked values using numpy.ma?

Time:09-02

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.

CodePudding user response:

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])
  • Related