最近 numpy 中的警告是:
In [738]: func1(A[1],1)
/usr/local/bin/ipython3:2: MaskedArrayFutureWarning: setting an item on
a masked array which has a shared mask will not copy the mask and also
change the original mask array in the future.
Check the NumPy 1.11 release notes for more information.
http://docs.scipy.org/doc/numpy/release.html#assigning-to-slices-views-of-maskedarray
当前,掩码数组的切片包含原始数据的视图和掩码的写时复制视图。因此,对切片遮罩的任何更改都将导致制作原始遮罩的副本,并且更改新遮罩而不是原始遮罩。
执行此操作后,A 的第 1 行仍被屏蔽,但A[
,:].data` 已更改。
In [757]: B=np.ma.masked_all((5))
...
In [759]: B[0]=5 # direct __setitem__ change to B
In [760]: B
Out[760]:
masked_array(data = [5.0 -- -- -- --],
mask = [False True True True True],
fill_value = 1e+20)
In [761]: func1(B[3:],1)
/usr/local/bin/ipython3:2: MaskedArrayFutureWarning: ....
In [762]: B # no change to mask
Out[762]:
masked_array(data = [5.0 -- -- -- --],
mask = [False True True True True],
fill_value = 1e+20)
In [763]: B.data # but data is changed
Out[763]: array([ 5., 0., 0., 1., 1.])
A[1,:]=1
是直接使用蒙版的__setitem__
,它可以完全负责设置data
和mask
。在您的函数A
中是原始视图,通过A.__getitem__
调用获得。显然,开发人员担心更改此视图的蒙版是否会影响原始蒙版。
我们可能要看看开发者的讨论;警告表明最近发生了一些变化。
=============
问题不在于函数中的使用,而在于视图
In [764]: B1=B[3:]
In [765]: B1[:]=2
/usr/local/bin/ipython3:1: MaskedArrayFutureWarning:...
In [766]: B
Out[766]:
masked_array(data = [5.0 -- -- -- --],
mask = [False True True True True],
fill_value = 1e+20)
In [767]: B.data
Out[767]: array([ 5., 0., 0., 2., 2.])
警告描述了现在发生的事情,并且可能会持续一段时间。据说这种做法会改变。
遵循更改说明建议:
In [785]: B1=B[3:]
In [787]: B1._sharedmask
Out[787]: True
In [790]: B1._sharedmask=False
In [791]: B1[:]=4
In [792]: B1
Out[792]:
masked_array(data = [4.0 4.0],
mask = [False False],
fill_value = 1e+20)
In [793]: B # mask has been changed along with data
Out[793]:
masked_array(data = [5.0 -- -- 4.0 4.0],
mask = [False True True False False],
fill_value = 1e+20)
如此变化
def func1(arr,val):
arr._sharedmask=False
arr[:]=val
将停止警告,并修改原始数组的掩码。