Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Sven's answer is the way to do it if you don't wish to further process matching values.<br> The following two examples return copies with only the matching values:</p> <pre><code>np.compress((25 &lt; a) &amp; (a &lt; 100), a).size </code></pre> <p>Or: </p> <pre><code>a[(25 &lt; a) &amp; (a &lt; 100)].size </code></pre> <p>Example interpreter session:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.random.randint(200,size=100) &gt;&gt;&gt; a array([194, 131, 10, 100, 199, 123, 36, 14, 52, 195, 114, 181, 138, 144, 70, 185, 127, 52, 41, 126, 159, 39, 68, 118, 124, 119, 45, 161, 66, 29, 179, 194, 145, 163, 190, 150, 186, 25, 61, 187, 0, 69, 87, 20, 192, 18, 147, 53, 40, 113, 193, 178, 104, 170, 133, 69, 61, 48, 84, 121, 13, 49, 11, 29, 136, 141, 64, 22, 111, 162, 107, 33, 130, 11, 22, 167, 157, 99, 59, 12, 70, 154, 44, 45, 110, 180, 116, 56, 136, 54, 139, 26, 77, 128, 55, 143, 133, 137, 3, 83]) &gt;&gt;&gt; np.compress((25 &lt; a) &amp; (a &lt; 100),a).size 34 &gt;&gt;&gt; a[(25 &lt; a) &amp; (a &lt; 100)].size 34 </code></pre> <p>The above examples use a "bit-wise and" (&amp;) to do an element-wise computation along the two boolean arrays which you create for comparison purposes.<br> Another way to write Sven's excellent answer, for example, is: </p> <pre><code>np.bitwise_and(25 &lt; a, a &lt; 100).sum() </code></pre> <p>The boolean arrays contain <code>True</code> values when the condition matches, and <code>False</code> when it doesn't.<br> A bonus aspect of boolean values is that <code>True</code> is equivalent to 1 and <code>False</code> to 0. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload