title: numpy reshaping multdimensional array through arbitrary axis
body: <p>so this is a question regarding the <strong>use of reshape and how this functions uses each axis on a multidimensional scale</strong>. </p>
  
  <p>Suppose I have the following array that contains matrices indexed by the first index. <strong>What I want to achieve is to instead index the columns of each matrix with the first index</strong>. In order to illustrate this problem, consider the following example where the given numpy array that indexes matrices with its first index is z.</p>
  
  <pre><code>x = np.arange(9).reshape((3, 3))
  y = np.arange(9, 18).reshape((3, 3))
  z = np.dstack((x, y)).T
  </code></pre>
  
  <p>Where z looks like:</p>
  
  <pre><code>array([[[ 0,  3,  6],
      [ 1,  4,  7],
      [ 2,  5,  8]],
  
     [[ 9, 12, 15],
      [10, 13, 16],
      [11, 14, 17]]])
  </code></pre>
  
  <p>And its shape is <code>(2, 3, 3)</code>. Here, the first index are the two images and the three x three is a matrix.  </p>
  
  <p>The question more specifically phrased then, is how to use reshape to obtain the following <strong>desired output</strong>:</p>
  
  <pre><code>array([[ 0,  1,  2],
     [ 3,  4,  5],
     [ 6,  7,  8],
     [ 9, 10, 11],
     [12, 13, 14],
     [15, 16, 17]])
  </code></pre>
  
  <p>Whose shape is <code>(6, 3)</code>. This achieves that the dimension of the array indexes the columns of the matrix x and y as presented above. My natural <em>inclination was to use reshape directly on z</em> in the following way:</p>
  
  <pre><code>out = z.reshape(2 * 3, 3)
  </code></pre>
  
  <p>But its output is the following which indexes the rows of the matrices and not the columns:</p>
  
  <pre><code>array([[ 0,  3,  6],
     [ 1,  4,  7],
     [ 2,  5,  8],
     [ 9, 12, 15],
     [10, 13, 16],
     [11, 14, 17]]
  </code></pre>
  
  <p>Could reshape be used to obtain the desired output above? Or <strong>more general, can you control how each axis is used when you use the reshape function</strong>?</p>
  
  <p>Two things:</p>
  
  <ul>
  <li><p>I know how to solve the problem. I can go through each element of the big matrix (z) transposed and then apply reshape in the way above. This increases computation time a little bit and is not really problematic. But it does not generalize and it does not feel python. So I was wondering if there is a standard enlightened way of doing this.</p></li>
  <li><p>I was not clear on how to phrase this question. If anyone has suggestion on how to better phrase this problem I am all ears.</p></li>
  </ul>