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>This is happening because when you return from np.delete, you get an array that is stored in b and a inside the loop. However, the arrays stored in the arrays variable are copies, not references. Hence, when you're updating the arrays by deleting them, it deletes with regard to the original arrays. The first loop will return the corrects indices of 0 in the array but the second loop will return ix as 4 (look at the original array).<br>Like if you display the arrays variable in each iteration, it is going to remain the same.<br><br>
You need to reassign arrays once you are done processing one array so that it's taken into consideration the next iteration. Here's how you'd do it - </p>

<pre><code>a = np.array([1, 2, 3, 0, 4, 5, 0])
b = np.array([1, 2, 3, 4, 0, 5, 6])
arrays = [a,b]
for i in range(0, len(arrays)):
  ix = np.where(arrays[i] == 0)
  b = np.delete(b, ix)
  a = np.delete(a, ix)
  arrays = [a, b]
</code></pre>

<p>Of course you can automate what happens inside the loop. I just wanted to give an explanation of what was happening.</p>

python arrays numpy indexing