2

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?

0

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @behzad.nouri I like the .mask.any() approach, since it can be applied after any series of mathematical operations.

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.