4

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]]]
1
  • I asked exactly the same question yesterday... Commented Nov 14, 2013 at 9:05

2 Answers 2

6

How about simply:

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

       [[999,   1,   1],
        [  1,   1,   1]]])
Sign up to request clarification or add additional context in comments.

Comments

1
a = np.piecewise(a, [a < 5, numpy.logical_and(a > 5,a <999) ,a >= 999], [0, 1,999])

I think would do what you want with one line ...

2 Comments

Even though this is a longer line than the one in my answer, (+1) for pointing out np.piecewise. :-) I did not know it existed.
Thank you, @Joran. But it seems a bit complicated for me :-)

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.