I'm working with 3D matrices in numpy. I'm actually passing these matrices to C using ctypes to carry out some calculation and then getting back a result. Now the thing is, my result is correct (I did the math on paper to verify), but it's just not in a form I want it to be.
Here's an example. I have a 3D array of the form:
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]]])
I need to convert it to a form where the ith columns of all 2D sub-matrices form a new 2D sub-matrix, as so:
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]]])
I have tried using various combinations of np.rot90
, np.flipud
, np.fliplr
, all to no avail. Any help on this would be greatly appreciated.
Thanks a lot!
答案 0 :(得分:2)
Your desired output is your initial array with the order of the axes reversed. That's how NumPy generalizes transposes to arbitrary-dimensional arrays, so you can use the T
attribute for this:
In [3]: x
Out[3]:
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]]])
In [4]: x.T
Out[4]:
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]]])