How can I mask part of an array with Numpy?

What I want to do is the β€œmask” of a subset of the array of elements j , from range 0 to k . For instance. For this array:

 [0.2, 0.1, 0.3, 0.4, 0.5] 

Masking the first two elements becomes

 [NaN, NaN, 0.3, 0.4, 0.5] 

Does masked_array support this operation?

+4
source share
2 answers
 In [51]: arr=np.ma.array([0.2, 0.1, 0.3, 0.4, 0.5],mask=[True,True,False,False,False]) In [52]: print(arr) [-- -- 0.3 0.4 0.5] 

Or, if you already have a numpy array, you can use np.ma.masked_less_equal (see the link for many other operations to mask individual elements):

 In [53]: arr=np.array([0.2, 0.1, 0.3, 0.4, 0.5]) In [56]: np.ma.masked_less_equal(arr,0.2) Out[57]: masked_array(data = [-- -- 0.3 0.4 0.5], mask = [ True True False False False], fill_value = 1e+20) 

Or, if you want to mask the first two elements:

 In [67]: arr=np.array([0.2, 0.1, 0.3, 0.4, 0.5]) In [68]: arr=np.ma.array(arr,mask=False) In [69]: arr.mask[:2]=True In [70]: arr Out[70]: masked_array(data = [-- -- 0.3 0.4 0.5], mask = [ True True False False False], fill_value = 1e+20) 
+5
source

I found this:

ma.array ([1,2,3,4], mask = [1,1,0,0]) masked_array (data = [- - 3 4], mask = [True True False False], fill_value = 999999)

+1
source

Source: https://habr.com/ru/post/1342447/


All Articles