title: How can I do this python list comprehension in NumPy?
body: <p>Let's say I have an array of values, <code>r</code>, which range anywhere from <code>0</code> to <code>1</code>. I want to remove all values that are some threshold value away from the median. Let's assume here that that threshold value is <code>0.5</code>, and <code>len(r) = 3000</code>. Then to mask out all values outside of this range, I can do a simple list comprehension, which I like:</p>
  
  <p><code>mask = np.array([ri &lt; np.median(r)-0.5 or ri &gt; np.median(r)+0.5 for ri in r])</code></p>
  
  <p>And if I use a timer on it:</p>
  
  <pre><code>import time
  import numpy as np
  
  start = time.time()
  r = np.random.random(3000)
  m = np.median(r)
  maxr,minr = m-0.5, m+0.5
  mask = [ri&lt;minr or ri&gt;maxr for ri in r]
  end = time.time()
  print('Took %.4f seconds'%(end-start))
  </code></pre>
  
  <p><code>&gt;&gt;&gt; Took 0.0010 seconds</code></p>
  
  <p>Is there a faster way to do this list comprehension and make the mask using <code>NumPy</code>?</p>
  
  <hr>
  
  <p><strong>Edit:</strong> </p>
  
  <p>I've tried several suggestions below, including:</p>
  
  <ul>
  <li><p>An element-wise or operator: <code>(r&lt;minv) | (r&gt;maxv)</code></p></li>
  <li><p>A Numpy logical or: <code>r[np.logical_or(r&lt;minr, r&gt;maxr)]</code></p></li>
  <li><p>A absolute difference boolean array: <code>abs(m-r) &gt; 0.5</code></p></li>
  </ul>
  
  <p>And here is the average time each one took after 300 runs through:</p>
  
  <pre><code>Python list comprehension: 0.6511 ms
  Elementwise or: 0.0138 ms
  Numpy logical or: 0.0241 ms
  Absolute difference: 0.0248 ms
  </code></pre>
  
  <p>As you can see, the elementwise Or was always the fastest, by nearly a factor of two (don't know how that would scale with array elements). Who knew. </p>