0

I am trying to find a way to get the mask from a masked array using only a logical expresion. So if var is a masked array, I would like to get the mask by comparing it to a nodata object, None or something similar along the lines

>>> var = numpy.ma.masked_array([1, 2 , 3], mask=[True, False, True])
>>> print var == None
... False
>>> print var == numpy.ma.masked
... --

What I would like to get

>>> print var == ???
... array([ True, False,  True], dtype=bool)

I know I can access the mask directly through var.mask, but in my use case I can only evaluate logical operators, such as numpy.equal.

Any idea what I could use for ??? to get the mask?

yellowcap
  • 3,985
  • 38
  • 51
  • Are there any limits on what you can put on the right side? For example, can you write a custom class with equality defined as `def __eq__(self, other): return other.mask`? – user2357112 Dec 10 '15 at 20:39

1 Answers1

0

If the fill_value does not otherwise occur in the array, this should work:

var.filled()==var.fill_value

A masked array has data and mask (as well as attributes like fill_value). The data is 'raw', that is, unchanged from what you supplied when creating the array. So the only way you can test the mask, is to either look directly at the mask, or apply the mask to the data, which is what filled does.

Stripped down, filled does:

m = self._mask
result = self._data.copy('K')
np.copyto(result, fill_value, where=m)

It makes a copy of the data, fills in the masked values with the fill.

Obviously this is a convoluted way of fetching the mask. But if you can't directly fetch the mask, you have do something like this.

You could use your own fill_value. masked .__eq__ does something like that (fills both sides with 0 and performs a normal __eq__.

In [416]: var.filled(0)==0
Out[416]: array([ True, False,  True], dtype=bool)

Explore the ma definition code for more details: /usr/lib/python3/dist-packages/numpy/ma/core.py

hpaulj
  • 221,503
  • 14
  • 230
  • 353