I have the following 3D array in Numpy:
a = np.array([[[1,2],[3,4]], [[5,6],[7,8]], [[9,10],[11,12]],[[13,14],[15,16]]])
when I write
b = np.reshape(a, [4,4])
The 2D resulting array will look like
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
However, I want it to be in this shape:
[[ 1 2 5 6]
[ 3 4 7 8]
[ 9 10 13 14]
[11 12 15 16]]
How can I do this efficiently in Python/Numpy?
Another approach using just
np.hstack
andnp.vstack
:Realizing the fact that your aim is to squash the first two slices of your original array into one slice and the next two into another slice and so on.
And you could also just replace the
np.vstack
andnp.hstack
with their fastest cousinnp.concatenate
, if you're concerned about performance.P.S.: This approach creates a new array leaving your original one unchanged.
Reshape to split the first axis into two, permute axes and one more reshape -
Making it generic, would become -
Sample run -