4

I'm trying to substitute some values in a numpy masked array, but my mask is being dropped:

import numpy as np
a = np.ma.array([1, 2, 3, -1, 5], mask=[0, 0, 0, 1, 0])
a[a < 2] = 999

The result is:

masked_array(data = [999 2 3 999 5],
mask = [False False False False False],
fill_value = 999999)

But what I want is:

masked_array(data = [999 2 3 -- 5],
mask = [False False False  True False],
fill_value = 999999)

What am I doing wrong? I'm using Python 2.7 and numpy 1.7.1 on Ubuntu 13.10

2
  • 4
    This is a long-standing gotcha/design-bug/feature with masked arrays. Basically, beware of assigning using boolean arrays when using masked arrays. A completely different (much cleaner) missing value system was added to numpy a few years back, but has been pulled back out until numpy 2.0 for various reasons. Commented Nov 13, 2013 at 15:13
  • @JoeKington, sigh. I suspected that. Commented Nov 13, 2013 at 15:24

1 Answer 1

4

I think you are not doing the substitution correctly, try this:

>>> import numpy as np
>>> a = np.ma.array([1, 2, 3, -1, 5], mask=[0, 0, 0, 1, 0])
>>> a.data[a < 2] = 999
>>> a
 masked_array(data = [999 2 3 -- 5],
         mask = [False False False  True False],
   fill_value = 999999)
Sign up to request clarification or add additional context in comments.

1 Comment

I have tested it on numpy 1.7.1

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.