Joseph Sheedy
Joseph Sheedy

Reputation: 6726

Unmasking an element by assignment in a 2D numpy MaskedArray

With a 1 dimensional numpy MaskedArray I can assign to an element which unmasks the array:

In [183]: x = np.ma.MaskedArray(data=np.zeros((2),dtype=float),mask=True)

In [184]: x[0] = 9

In [185]: x
Out[185]:
masked_array(data = [9.0 --],
         mask = [False  True],
   fill_value = 1e+20)

With a 2 dimensional array, assigning to a single value does not unmask the array:

In [186]: x = np.ma.MaskedArray(data=np.zeros((2,2),dtype=float),mask=True)

In [187]: x[0][0] = 9

In [188]: x
Out[188]:
masked_array(data =
 [[-- --]
 [-- --]],
             mask =
 [[ True  True]
 [ True  True]],
       fill_value = 1e+20)

If I assign to a slice, the slice gets unmasked

In [189]: x[0] = 9

In [190]: x
Out[190]:
masked_array(data =
 [[9.0 9.0]
 [-- --]],
             mask =
 [[False False]
 [ True  True]],
       fill_value = 1e+20)

How can I assign to a single value to unmask it?

Upvotes: 0

Views: 253

Answers (1)

user2357112
user2357112

Reputation: 280973

x[0, 0] = 9

It looks like when you execute x[0][0] = 9, NumPy decouples the x[0] temporary's mask from x's mask, so the assignment only unmasks the x[0] temporary. The relevant code is in numpy/ma/core.py:

            # Unshare the mask if necessary to avoid propagation
            if not self._isfield:
                self.unshare_mask()
                _mask = ndarray.__getattribute__(self, '_mask')

I don't know why it does that.

Upvotes: 2

Related Questions