Numpy indexing: Set values of an array given by conditions in different array
<p>I want to set all values of an array to 0 that have values that are not in a different array.</p>

<p>Easy if it's only one condition:</p>

<pre><code>a = np.array([[1,2],[2,4],[5,6]])
cond = 1
a[a!=cond] = 0
</code></pre>

<p>What about if I have a list of conditions, e.g. </p>

<pre><code>cond = np.array([1,2,6])
</code></pre>

<p>I can write it out like this</p>

<pre><code>a[(a!=1) &amp; (a!=2) &amp; (a!=6)]=0
</code></pre>

<p>but I can't figure out the general way of doing this, something like this</p>

<pre><code>a[a!=cond] = 0
</code></pre>

<p>when <code>cond</code> is an array. I also looked at <code>np.select</code> but that doesn't seem to do what I need.</p>

<p>Well, there's the function <code>np.in1d</code> which tests if the first array<br>
contains any of the items from the second array. <br>
But since this works on 1d arrays, and you need to test on a 2d array<br>
the solution is a bit tricky, using the fact that <code>ravel()</code> returns a view:</p>

<pre><code>a = np.array([[1,2],[2,4],[5,6]])
a.ravel()[~np.in1d(a.ravel(), [1, 2, 6])] = 0
print(a)
</code></pre>

<p>And then you get the output:</p>

<pre><code>[[1 2]
 [2 0]
 [0 6]]
</code></pre>

python numpy indexing