简体   繁体   中英

Masked array operation in numpy

This is my fist post on stack overflow , so please bear with me. Of course I tried to find the answer online, but without success.

The problem:

In [1]: import numpy
In [2]: import numpy.ma as ma
In [4]: a = ma.array([[[1,2],[3,4]],[[1,2],[3,4]]], mask=[[[True,False],[False,False]],[[False,False],[False,True]]])
In [5]: a
Out[5]: 
masked_array(data =
 [[[-- 2]
  [3 4]]

 [[1 2]
  [3 --]]],
             mask =
 [[[ True False]
  [False False]]

 [[False False]
  [False  True]]],
       fill_value = 999999)

In [6]: ma.mean(a, axis=0)
Out[6]: 
masked_array(data =
 [[1.0 2.0]
 [3.0 4.0]],
             mask =
 [[False False]
 [False False]],
       fill_value = 1e+20)

But i expect the mean function to return masked output, as in;

In [7]: (a[0]+a[1])/2
Out[7]: 
masked_array(data =
 [[-- 2]
 [3 --]],
             mask =
 [[ True False]
 [False  True]],
       fill_value = 999999)

Where am I doing something wrong here?

Masked arrays ignore masked values, they do not propagate the mask. To get the result that you want, you may do:

>>> np.ma.array(a.data.mean(axis=0), mask=a.mask.any(axis=0))
masked_array(data =
 [[-- 2.0]
 [3.0 --]],
             mask =
 [[ True False]
 [False  True]],
       fill_value = 1e+20)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM