update numpy array where not masked
<p>My question is twofolded</p>

<p>First, lets say I've two numpy arrays, that are partially masked</p>

<pre><code>array_old
[[-- -- -- --]
 [10 11 -- --]
 [12 14 -- --]
 [-- -- 17 --]]

array_update
[[--  5 -- --]
 [-- --  9 --]
 [-- 15  8 13]
 [-- -- 19 16]]
</code></pre>

<p>How to get create a new array, where all non-masked values are updated or ammended, like:</p>

<pre><code>array_new
[[--  5 -- --]
 [10 11  9 --]
 [12 15  8 13]
 [-- -- 19 16]]
</code></pre>

<p>Secondly,
If possible, how to do above in a 3d numpy array?</p>

<p><strong>UPDATE:</strong></p>

<p>For the second part, now I use a for loop, using <a href="https://stackoverflow.com/a/39869892/2459096">@freidrichen</a> method as follows:</p>

<pre><code>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()
</code></pre>

<p>Not sure if that's the best solution</p>

<p>Use <code>a[~b.mask] = b.compressed()</code>.</p>

<p><code>a[~b.mask]</code> selects all the values in <code>a</code> where <code>b</code> is not masked. <code>b.compressed()</code> is a flattened array with all the non-masked values in <code>b</code>.</p>

<p>Example:</p>

<pre><code>&gt;&gt;&gt; a = np.ma.masked_equal([[0, 0, 0, 0], [10, 11, 0, 0], [12, 14, 0, 0], [0, 0, 17, 0]], 0)
&gt;&gt;&gt; b = np.ma.masked_equal([[0, 5, 0, 0], [0, 0, 9, 0], [0, 15, 8, 13], [0, 0, 19, 16]], 0)
&gt;&gt;&gt; a[~b.mask] = b.compressed()
&gt;&gt;&gt; a
[[-- 5 -- --]
[10 11 9 --]
[12 15 8 13]
[-- -- 19 16]]
</code></pre>

<p>This should work with 3d arrays too.</p>

python arrays numpy