title: Dynamic axis indexing of Numpy ndarray
body: <p>I want to obtain the 2D slice in a given direction of a 3D array where the <code>direction</code> (or the axis from where the slice is going to be extracted) is given by another variable.</p>
  
  <p>Assuming <code>idx</code> the index of the 2D slice in a 3D array, and <code>direction</code> the axis in which obtain that 2D slice, the initial approach would be:</p>
  
  <pre><code>if direction == 0:
      return A[idx, :, :]
  elif direction == 1:
      return A[:, idx, :]
  else:
      return A[:, :, idx]
  </code></pre>
  
  <p>I'm pretty sure there must be a way of doing this without doing conditionals, or at least, not in raw python. Does numpy have a shortcut for this? </p>
  
  <p>The better solution I've found so far (for doing it dynamically), relies in the transpose operator:</p>
  
  <pre><code># for 3 dimensions [0,1,2] and direction == 1 --&gt; [1, 0, 2]
  tr = [direction] + range(A.ndim)
  del tr[direction+1]
  
  return np.transpose(A, tr)[idx]
  </code></pre>
  
  <p>But I wonder if there is any better/easier/faster function for this, since for 3D the transpose code almost looks more awful than the 3 if/elif. It generalizes better for ND and the larger the N the more beautiful the code gets in comparison, but for 3D is quite the same.</p>