Justin Olbrantz
Justin Olbrantz

Reputation: 649

Can you assign only unmasked values using numpy.ma?

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.

Upvotes: 0

Views: 576

Answers (1)

9769953
9769953

Reputation: 12201

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

Upvotes: 1

Related Questions