在 Numpy 中切片蒙面数组时如何保留蒙面?
How do I keep the mask when slicing a masked array in Numpy?
当我创建 Numpy 掩码数组的视图(通过切片)时,掩码被复制到视图中——这样视图的更新就不会改变掩码原始(但会更改原始数组中的数据)。
我想要的是更新视图时原始数据和原始掩码
When accessing a slice, the output is a masked array whose data attribute
is a view of the original data, and whose mask is either nomask (if there
was no invalid entries in the original array) or a copy of the
corresponding slice of the original mask. The copy is required to avoid
propagation of any modification of the mask to the original.
例子
import numpy.ma as ma
orig_arr = ma.array([[11,12],[21,22]])
orig_arr[1,:] = ma.masked
print orig_arr
## Prints: [[11 12]
## [-- --]]
view_arr = orig_arr[1,:]
print view_arr
## Prints: [-- --]
view_arr[:] = [31,32]
print view_arr
## Prints: [31 32]
print orig_arr
## Prints: [[11 12]
## [-- --]]
print orig_arr.data[1,:]
## Prints: [31 32]
可以看到原来数组中的数据已经更新了,但是
面具没有。
如何使视图中的更新影响原始数组中的掩码?
尝试在更改值之前关闭视图中的遮罩
orig_arr = ma.array([[11,12],[21,22]])
orig_arr[1,:] = ma.masked
print orig_arr
## Prints: [[11 12]
## [-- --]]
view_arr = orig_arr[1,:]
print view_arr
## Prints: [-- --]
view_arr.mask=False # or [True, False]
view_arr[:] = [31,32]
print view_arr
## Prints: [31 32] #or [-- 32]
print orig_arr
## Prints: [[11 12]
## [31 32]] # or [-- 32]
当我创建 Numpy 掩码数组的视图(通过切片)时,掩码被复制到视图中——这样视图的更新就不会改变掩码原始(但会更改原始数组中的数据)。
我想要的是更新视图时原始数据和原始掩码
When accessing a slice, the output is a masked array whose data attribute is a view of the original data, and whose mask is either nomask (if there was no invalid entries in the original array) or a copy of the corresponding slice of the original mask. The copy is required to avoid propagation of any modification of the mask to the original.
例子
import numpy.ma as ma
orig_arr = ma.array([[11,12],[21,22]])
orig_arr[1,:] = ma.masked
print orig_arr
## Prints: [[11 12]
## [-- --]]
view_arr = orig_arr[1,:]
print view_arr
## Prints: [-- --]
view_arr[:] = [31,32]
print view_arr
## Prints: [31 32]
print orig_arr
## Prints: [[11 12]
## [-- --]]
print orig_arr.data[1,:]
## Prints: [31 32]
可以看到原来数组中的数据已经更新了,但是 面具没有。
如何使视图中的更新影响原始数组中的掩码?
尝试在更改值之前关闭视图中的遮罩
orig_arr = ma.array([[11,12],[21,22]])
orig_arr[1,:] = ma.masked
print orig_arr
## Prints: [[11 12]
## [-- --]]
view_arr = orig_arr[1,:]
print view_arr
## Prints: [-- --]
view_arr.mask=False # or [True, False]
view_arr[:] = [31,32]
print view_arr
## Prints: [31 32] #or [-- 32]
print orig_arr
## Prints: [[11 12]
## [31 32]] # or [-- 32]