For a python project I often find myself reshaping and re-arranging n-dimensional numpy arrays. However, I have a hard time to determine how to approach the problem, visualize the outcome of the results of the reshaping methods and knowing my solution is efficient.
At the moment when confronted with such a problem my strategy is to start ipython, load some sample data and go trial and error until I find a combination of transpose()s, reshape()s and swapaxes()s. which gets the desired result. It gets the job done, but without a real understanding of what is going on and often produces code which is hard to maintain.
So, my question is about finding a strategy. How do you approach such a problem? How do you visualize an ndarray in your head when you have to shape it in the desired format? How do you come to the right actions?
To make answering a bit more concrete, an example to play with:
Assume you want to reshape the following 3d-array
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
to a 2d-array where the first columns from the 3rd dimension are placed first, the 2nd columns second, ....etc
The result should look like this:
array([[ 0, 9, 18, 3, 12, 21, 6, 15, 24],
[ 1, 10, 19, 4, 13, 22, 7, 16, 25],
[ 2, 11, 20, 5, 14, 23, 8, 17, 26]])
PS. also any reading material on the subject would be great!