I would like to assign to (a slice of) a masked numpy array but not modify the mask. (Assignment normally clears the mask (unless it is "hard"), which seems completely contrary to the point of masking, but that's what we've got to work with.) I would also like this routine to work for plain unmasked arrays.
Is there a better way to do this than saving and restoring the mask?
a = np.ma.array([0, 1, 2], mask=[0, 1, 0])
mask = a.mask.copy() if np.ma.is_masked(a) else None # Have to copy because it might be shared
a[a < 2] = -1
if mask is not None:
a.mask = mask
print(a, a.data)
# [-1 -- 2] [-1 -1 2]
This is Python 2, numpy 1.11.1.