Numpy boolean indexing issue
<p>Here is my code snippet that uses numpy</p>

<pre><code>import numpy as np
n = 10
arr = np.array(range(n))
print(arr)
selection = [i % 2 == 0 for i in range(n)]
print(selection)
neg_selection = np.invert(selection)
print(neg_selection)

print(arr[selection])
print(arr[neg_selection])
</code></pre>

<p>The above code prints:</p>

<pre><code>[0 1 2 3 4 5 6 7 8 9]
[True, False, True, False, True, False, True, False, True, False]
[False  True False  True False  True False  True False  True]
[1 0 1 0 1 0 1 0 1 0]
[1 3 5 7 9]
</code></pre>

<p>the last two expected prints are:</p>

<pre><code>[0 2 4 6 8]
[1 3 5 7 9]
</code></pre>

<p>What is wrong here?</p>

<p>looks like numpy has trouble dealing with <code>list</code> of <code>boolean</code>s.</p>

<pre><code>n = 10
arr = np.array(range(n))
selection = [i % 2 == 0 for i in range(n)]
neg_selection = np.invert(selection)

print(type(selection), arr[selection])
print(type(neg_selection), arr[neg_selection])
</code></pre>

<p>It produced:</p>

<pre><code>&lt;type 'list'&gt; [1 0 1 0 1 0 1 0 1 0]
&lt;type 'numpy.ndarray'&gt; [1 3 5 7 9]
</code></pre>

<p>Noticed that the trouble here is due to <code>&lt;type 'list'&gt;</code>.
So, change the selection object to numpy array</p>

<pre><code>selection = np.array([i % 2 == 0 for i in range(n)])
</code></pre>

<p>Or, even simpler:</p>

<pre><code>selection = arr % 2 == 0
</code></pre>

<p>Then it worked.</p>

python numpy