title: Is there a way to get the top k values per row of a numpy array (Python)?
body: <p>Given a numpy array of the form below:</p>
  
  <pre><code>x = [[4.,3.,2.,1.,8.],[1.2,3.1,0.,9.2,5.5],[0.2,7.0,4.4,0.2,1.3]]
  </code></pre>
  
  <p>is there a way to retain the top-3 values in each row and set others to zero in python (without an explicit loop). The result in the case of the example above would be </p>
  
  <pre><code>x = [[4.,3.,0.,0.,8.],[0.,3.1,0.,9.2,5.5],[0.0,7.0,4.4,0.0,1.3]]
  </code></pre>
  
  <p>Code for one example</p>
  
  <pre><code>import numpy as np
  arr = np.array([1.2,3.1,0.,9.2,5.5,3.2])
  indexes=arr.argsort()[-3:][::-1]
  a = list(range(6))
  A=set(indexes); B=set(a)
  zero_ind=(B.difference(A)) 
  arr[list(zero_ind)]=0
  </code></pre>
  
  <p>The output:</p>
  
  <pre><code>array([0. , 0. , 0. , 9.2, 5.5, 3.2])
  </code></pre>
  
  <p>Above is my sample code (with many lines) for a 1-D numpy array. Looping through each row of a numpy array and performing this same computation repeatedly would be quite expensive. Is there a simpler way?</p>