Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to replace values in masked array according to a condition

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]]]
like image 363
natalia Avatar asked Mar 21 '23 16:03

natalia


2 Answers

How about simply:

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

       [[999,   1,   1],
        [  1,   1,   1]]])
like image 60
NPE Avatar answered Apr 06 '23 08:04

NPE


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 ...

like image 36
Joran Beasley Avatar answered Apr 06 '23 08:04

Joran Beasley