Python: how to replace values in masked array according to a condition
Question: I have an array. I want to replace the values `> 5` with `1`, and the values
`<= 5` with `0`. I also must to take into account the invalid values (`999`).

1) My array:

    
    
    >>> import numpy
    >>> a = numpy.array([   [[2, 5, 999],[0, 12, 1]], [[999, 8, 7],[7, 11, 6]]   ])
    >>> a
    array([[[  2,   5, 999],
            [  0,  12,   1]],
    
           [[999,   8,   7],
            [  7,  11,   6]]])
    

2) I mask the invalid values:

    
    
    >>> mask_a = (a==999)
    >>> a_masked = numpy.ma.masked_array(a, mask = mask_a)
    >>> print a_masked
    [[[2 5 --]
      [0 12 1]]
    
     [[-- 8 7]
      [7 11 6]]]
    

3) I replace the values <= 5 with zeros:

    
    
    >>> a_masked[a_masked<=5]=0
    >>> print a_masked
    [[[0 0 --]
      [0 12 0]]
    
     [[-- 8 7]
      [7 11 6]]]
    

4) I want to replace now the values > 5 with ones:

    
    
    >>> a_masked[a_masked>5]=1
    >>> print a_masked
    [[[0 0 1]
      [0 1 0]]
    
     [[1 1 1]
      [1 1 1]]]
    

Why doesn't it take into account the values=999 which were already masked???

I want to get the following result:

    
    
        [[[0 0 --]
          [0 1 0]]
    
         [[-- 1 1]
          [1 1 1]]]
    


Answer: How about simply:

    
    
    >>> a[a != 999] = (a[a != 999] > 5)
    >>> a
    array([[[  0,   0, 999],
            [  0,   1,   0]],
    
           [[999,   1,   1],
            [  1,   1,   1]]])
    

