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>A slow method involves operating over the whole list twice, first to build an intermediate list of indices to delete, and then second to delete all of the values at those indices:</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]
vals = []

for array in arrays:
    ix = np.where(array == 0)
    vals.extend([y for x in ix for y in x.tolist()])

vals = list(set(vals))

new_array = []
for array in arrays:
    new_array.append(np.delete(array, vals))
</code></pre>

python arrays numpy indexing