更新未屏蔽的numpy数组 [英] update numpy array where not masked
问题描述
我的问题是双重的
首先,假设我有两个被部分屏蔽的numpy数组
First, lets say I've two numpy arrays, that are partially masked
array_old
[[-- -- -- --]
[10 11 -- --]
[12 14 -- --]
[-- -- 17 --]]
array_update
[[-- 5 -- --]
[-- -- 9 --]
[-- 15 8 13]
[-- -- 19 16]]
如何创建一个新的数组,其中所有未屏蔽的值都将被更新或修改,例如:
How to get create a new array, where all non-masked values are updated or ammended, like:
array_new
[[-- 5 -- --]
[10 11 9 --]
[12 15 8 13]
[-- -- 19 16]]
第二, 如果可能,如何在3d numpy数组中执行上述操作?
Secondly, If possible, how to do above in a 3d numpy array?
更新:
第二部分,现在我使用一个for循环,使用 @freidrichen 方法,如下所示:
For the second part, now I use a for loop, using @freidrichen method as follows:
array = np.ma.masked_equal([[[0, 0, 0, 0], [10, 11, 0, 0], [12, 14, 0, 0], [0, 0, 17, 0]],[[0, 5, 0, 0], [0, 0, 9, 0], [0, 15, 8, 13], [0, 0, 19, 16]],[[0, 0, 0, 0], [5, 0, 0, 13], [8, 14, 0, 0], [0, 0, 17, 0]],[[6, 7, 8, 9], [0, 0, 0, 0], [0, 0, 0, 21], [0, 0, 0, 0]]], 0)
a = array[0,::]
for ix in range(array.shape[0] - 1):
b = array[ix,::]
c = array[ix+1,::]
b[~c.mask] = c.compressed()
a[~b.mask] = b.compressed()
不确定这是否是最佳解决方案
Not sure if that's the best solution
推荐答案
使用a[~b.mask] = b.compressed()
.
a[~b.mask]
选择a
中未屏蔽b
的所有值. b.compressed()
是具有b
中所有非掩码值的扁平化数组.
a[~b.mask]
selects all the values in a
where b
is not masked. b.compressed()
is a flattened array with all the non-masked values in b
.
示例:
>>> a = np.ma.masked_equal([[0, 0, 0, 0], [10, 11, 0, 0], [12, 14, 0, 0], [0, 0, 17, 0]], 0)
>>> b = np.ma.masked_equal([[0, 5, 0, 0], [0, 0, 9, 0], [0, 15, 8, 13], [0, 0, 19, 16]], 0)
>>> a[~b.mask] = b.compressed()
>>> a
[[-- 5 -- --]
[10 11 9 --]
[12 15 8 13]
[-- -- 19 16]]
这也应该适用于3d阵列.
This should work with 3d arrays too.
这篇关于更新未屏蔽的numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!