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>

<pre><code>In [63]: arr=np.arange(10)
In [64]: arr
Out[64]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [65]: mask = [n%2==0 for n in arr]
In [66]: mask
Out[66]: [True, False, True, False, True, False, True, False, True, False]
</code></pre>

<p>Trying to index with this list:</p>

<pre><code>In [67]: arr[mask]
/usr/local/bin/ipython3:1: FutureWarning: in the future, boolean array-likes will be handled as a boolean array index
  #!/usr/bin/python3
Out[67]: array([1, 0, 1, 0, 1, 0, 1, 0, 1, 0])
</code></pre>

<p>It's treating your list as a list of index integers, not booleans; same as:</p>

<pre><code>In [72]: arr[[3,0,2,0,1,0,5,0,2]]
Out[72]: array([3, 0, 2, 0, 1, 0, 5, 0, 2])
</code></pre>

<p>I wondered why you used <code>np.invert</code>, but then realized that with a list, <code>~</code> doesn't work:</p>

<pre><code>In [68]: arr[~mask]
...

TypeError: bad operand type for unary ~: 'list'
</code></pre>

<p><code>invert</code> turns the list into an array and does the <code>not</code></p>

<pre><code>In [69]: np.invert(mask)
Out[69]: array([False,  True, False,  True, False,  True, False,  True, False,  True], dtype=bool)
In [70]: arr[np.invert(mask)]
Out[70]: array([1, 3, 5, 7, 9])
</code></pre>

<p>and we can <code>not</code> that array:</p>

<pre><code>In [71]: arr[~np.invert(mask)]
Out[71]: array([0, 2, 4, 6, 8])
</code></pre>

<p>Or if I create the mask <code>array</code> right from the start:</p>

<pre><code>In [73]: mask = np.array([n%2==0 for n in arr])
In [74]: arr[mask]
Out[74]: array([0, 2, 4, 6, 8])
</code></pre>

<p>So basically, don't try to use a boolean list as a mask.  Use a boolean array.</p>

python numpy