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>Crux of the solution is : </p>

<p><code>NOT( option1) &amp; NOT(option2) &amp; NOT(option3)</code> would be an equivalent of</p>

<p><code>NOT (option1 | option2 | option3 )</code>. </p>

<p>Now, to get the mask for <code>option1 | option2 | option3</code>, we have a built-in <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a>. So, basically the solution would be somewhat like <code>~np.in1d(a,cond)</code>. Since <code>np.in1d</code> works on 1D array, we need to reshape it afterwards before using the mask on the input array for setting values as zeros.</p>

<p>Thus, the implementation would look something like this -</p>

<pre><code>a[~np.in1d(a,cond).reshape(a.shape)] = 0
</code></pre>

python numpy indexing