Reputation: 13930
My question is twofolded
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]]
Secondly, If possible, how to do above in a 3d numpy array?
UPDATE:
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
Upvotes: 2
Views: 786
Reputation: 2576
Use a[~b.mask] = b.compressed()
.
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
.
Example:
>>> 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]]
This should work with 3d arrays too.
Upvotes: 5