Numpy.ma:保持蒙版数组链接到它的构建块(浅拷贝?)

时间:2015-11-12 10:01:08

标签: python numpy

如果要构建蒙版数组,请使用:

class myclass(object):
    def __init__(self, data, mask):
        self.masked_array = numpy.ma(data, mask=mask)

当我更改蒙版数组时,我想要更改蒙版和数据。喜欢:

data = [1,2,3]
mask = [True, False, False]
c = myclass(data, mask)
c.masked_array.mask[0] = False  # this will not change mask

显而易见的答案是在构建对象后链接:

c = myclass(data, mask) 
data = c.masked_array.data
mask = c.masker_array.mask

而且,尽管它有效,但在我的非简化问题中,为此做这件事真是太糟糕了。还有其他选择吗?

我正在使用numpy 1.10.1和python 2.7.9。

1 个答案:

答案 0 :(得分:1)

The mask is itself a numpy array, so when you give a list as the mask, the values in the mask must be copied into a new array. Instead of using a list, pass in a numpy array as the mask.

For example, here are two arrays that we'll use to construct the masked array:

In [38]: data = np.array([1, 2, 3])

In [39]: mask = np.array([True, False, False])

Create our masked array:

In [40]: c = ma.masked_array(data, mask=mask)

In [41]: c
Out[41]: 
masked_array(data = [-- 2 3],
             mask = [ True False False],
       fill_value = 999999)

Change c.mask in-place, and see that mask is also changed:

In [42]: c.mask[0] = False

In [43]: mask
Out[43]: array([False, False, False], dtype=bool)

It is worth noting that the masked_array constructor has the argument copy. If copy is False (the default), the constructor doesn't copy the input arrays, and instead uses the given references (but it can't do that if the inputs are not already numpy arrays). If you use copy=True, then even input arrays will be copied--but that's not what you want.