4

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.

2 Answers 2

3

I think what you want can be done by:

a.data[a < 2] = -1
Sign up to request clarification or add additional context in comments.

Comments

1

In researching the question, I found an answer:

np.copyto(a, -1, where=a < 2)

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.