title: Extract fixed number of elements per row in numpy array
body: <p>Suppose I have an array <code>a</code>, and a boolean array <code>b</code>, I want to extract a fixed number of elements from the valid elements in each row of <code>a</code>. The valid elements are the ones indicated by <code>b</code>.</p>
  <p>Here is an example:</p>
  <pre><code>a = np.arange(24).reshape(4,6)
  b = np.array([[0,0,1,1,0,0],[0,1,0,1,0,1],[0,1,1,1,1,0],[0,0,0,0,1,1]]).astype(bool)
  x = []
  for i in range(a.shape[0]):
      c = a[i,b[i]]
      d = np.random.choice(c, 2)
      x.append(d)
  </code></pre>
  <p>Here I used a for loop, which will be slow in case these arrays are big and high-dimensional. Is there a more efficient way to do this? Thanks.</p>