2

I have foll.. 2 numpy arrays:

arr_a = numpy.zeros(shape=(3, 3))

arr_b is second numpy array, but it is masked with mask value of -9999.0

if I do:

arr_a += arr_b

then the resulting arr_a does not retain the mask. How can I get an array in return that retains the mask?

1 Answer 1

3

I'm assuming that arr_b is an instance of numpy.ma.array. In such a case the semantics of numpy mean that arr_a += arr_b is adding the array in-place. Thus, it certainly cannot alter its type from a numpy.array to a numpy.ma.array.

This is in contrast to arr_a + arr_b which is creating a new output array so is free to allocate it as it wishes.

If you wish to do an in-place add of a masked array, you must cast your target (arr_a) to be a masked array as well.

>>> arr_a = ma.asarray(arr_a)
>>> arr_a += arr_b
Sign up to request clarification or add additional context in comments.

1 Comment

yes ... however if you are wanting to repeatedly do additions, bear in mind that in-place add's (+=) are more efficient as they do not require memory allocation.

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.