2

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

1
  • @holdenweb you are right, let me update and yes, where new non-masked values are available it should overwrite existing ones Commented Oct 5, 2016 at 9:45

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your great answer! What I actually ment with 3d arrays, is that one 3d array contains several 2d arrays/slices [as array_update1, array_update2], where the output is a 2d array filled with the most 'recent' values [and maybe no masked values anymore]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.