Indexing an array with a logical array of the same shape in Python
<p>I would like to be able to do:</p>

<pre><code>a = [1,2,3]
a[[True, True, False]]
&gt;&gt; array([1,2])
</code></pre>

<p>I just can't find the simple way how... Thanks!</p>

<p>If <code>a</code> and the mask are truly Python arrays, then you can do a simple list comprehension:</p>

<pre><code>arr = [1,2,3]
mask = [True, True, False]
[a for a, m in zip(arr, mask) if m]
</code></pre>

<p>If you are OK with additional imports, you can use @moses-koledoye's suggestion of using <code>itertools.compress</code>.</p>

<p>If on the other hand you are using <code>numpy</code>, as the final output of <code>array([1,2])</code> suggests, you can just do the indexing directly:</p>

<pre><code>import numpy as np
arr = np.array([1, 2, 3])
mask = np.array([True, True, False])
arr[mask]
</code></pre>

<p>Note that mask has to be an actual <code>np.boolean</code> array. You can not just use a Python list like <code>[True, True, False]</code>. This is because <code>np.array.__getitem__</code> checks if the input is exactly another array. If not, the input is converted to integers, so you end up effectively indexing with <code>[1, 1, 0]</code> instead of a mask. You can get a lot more details on this particular tangential issue here: <a href="http://stackoverflow.com/a/39168021/2988730">http://stackoverflow.com/a/39168021/2988730</a></p>

python