reordering of numpy arrays

Check out rollaxis, a function which shifts the axes around, allowing you to reorder your array in a single command. If im has shape i, j, k

rollaxis(im, 2)

should return an array with shape k, i, j.

After this, you can flatten your array, ravel is a clear function for this purpose. Putting this all together, you have a nice one-liner:

new_im_vec = ravel(rollaxis(im, 2))

new_im = im.swapaxes(0,2).swapaxes(1,2) # First swap i and k, then i and j
new_im_vec = new_im.flatten() # Vectorize

This should be much faster because swapaxes returns a view on the array, rather than copying elements over.

And of course if you want to skip new_im, you can do it in one line, and still only flatten is doing any copying.

new_im_vec = im.swapaxes(0,2).swapaxes(1,2).flatten()

Tags:

Python

Numpy