title: How to replace only the first n elements in a numpy array that are larger than a certain value?
body: <p>I have an array <code>myA</code> like this:</p>
  
  <pre><code>array([ 7,  4,  5,  8,  3, 10])
  </code></pre>
  
  <p>If I want to replace all values that are larger than a value <code>val</code> by 0, I can simply do:</p>
  
  <pre><code>myA[myA &gt; val] = 0
  </code></pre>
  
  <p>which gives me the desired output (for <code>val = 5</code>):</p>
  
  <pre><code> array([0, 4, 5, 0, 3, 0])
  </code></pre>
  
  <p>However, my goal is to replace not all but only the first <code>n</code> elements of this array that are larger than a value <code>val</code>.</p>
  
  <p>So, if <code>n = 2</code> my desired outcome would look like this (<code>10</code> is the third element and should therefore not been replaced):</p>
  
  <pre><code>array([ 0,  4,  5,  0,  3, 10])
  </code></pre>
  
  <p>A straightforward implementation would be:</p>
  
  <pre><code>import numpy as np
  
  myA = np.array([7, 4, 5, 8, 3, 10])
  n = 2
  val = 5
  
  # track the number of replacements
  repl = 0
  
  for ind, vali in enumerate(myA):
  
      if vali &gt; val:
  
          myA[ind] = 0
          repl += 1
  
          if repl == n:
              break
  </code></pre>
  
  <p>That works but maybe someone can can up with a smart way of masking!?</p>