Deleting values from multiple arrays that have a particular value
<p>Lets say I have two arrays: <code>a = array([1,2,3,0,4,5,0])</code> and <code>b = array([1,2,3,4,0,5,6])</code>. I am interested in removing the instances where <code>a</code> and <code>b</code>are <code>0</code>. But I also want to remove the corresponding instances from both lists. Therefore what I want to end up with is <code>a = array([1,2,3,5])</code> and <code>b = array([1,2,3,5])</code>. This is because <code>a[3] == 0</code> and <code>a[6] == 0</code>, so both <code>b[3]</code> and <code>b[6]</code> are also deleted. Likewise, since <code>b[4] == 0</code>, <code>a[4]</code> is also deleted.Its simple to do this for say two arrays:</p>

<pre><code>import numpy as np
a = np.array([1,2,3,0,4,5,0])
b = np.array([1,2,3,4,0,5,6])

ix = np.where(b == 0)
b = np.delete(b, ix)
a = np.delete(a, ix)

ix = np.where(a == 0)
b = np.delete(b, ix)
a = np.delete(a, ix)
</code></pre>

<p>However this solution doesnt scale up if I have many many arrays (which I do). What would be a more elegant way to do this?</p>

<p>If I try the following:</p>

<pre><code>import numpy as np

a = np.array([1,2,3,0,4,5,0])
b = np.array([1,2,3,4,0,5,6])

arrays = [a,b]

for array in arrays:
    ix = np.where(array == 0)
    b = np.delete(b, ix)
    a = np.delete(a, ix)
</code></pre>

<p>I get <code>a = array([1, 2, 3, 4])</code> and <code>b = array([1, 2, 3, 0])</code>, not the answers I need. Any idea where this is wrong?</p>

<p>Assuming both/all arrays always have the same length, you can use <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">masks</a>:</p>

<pre><code>ma = a != 0 # mask elements which are not equal to zero in a
mb = b != 0 # mask elements which are not equal to zero in b
m = ma * mb # assign the intersection of ma and mb to m
print a[m], b[m] # [1 2 3 5] [1 2 3 5]
</code></pre>

<p>You can of course also do it in one line</p>

<pre><code>m = (a != 0) * (b != 0)
</code></pre>

<p>Or use the inverse</p>

<pre><code>ma = a == 0
mb = b == 0
m = ~(ma + mb) # not the union of ma and mb
</code></pre>

python arrays numpy indexing