Trying to transpose each numpy array in my numpy array.
Here is an example of what I want:
A:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
A Transpose:
[[[ 1 4]
[ 2 5]
[ 3 6]]
[[ 7 10]
[ 8 11]
[ 9 12]]]
Tried doing this using np.apply_along_axis function but was not getting the correct results.I am trying to apply this to a very large array and any help would be greatly appreciated!
A=np.arange(1,13).reshape(2,2,3)
A=np.apply_along_axis(np.transpose, 0, A)
You need to swap the second and third axises, for which you can use either np.swapaxes
:
A.swapaxes(1,2)
#array([[[ 1, 4],
# [ 2, 5],
# [ 3, 6]],
# [[ 7, 10],
# [ 8, 11],
# [ 9, 12]]])
or transpose
:
A.transpose(0,2,1)
#array([[[ 1, 4],
# [ 2, 5],
# [ 3, 6]],
# [[ 7, 10],
# [ 8, 11],
# [ 9, 12]]])
For the sake of completeness, there are is also moveaxis
which replaces the deprecated rollaxis
:
>>> np.rollaxis(A, 2, 1)
array([[[ 1, 4],
[ 2, 5],
[ 3, 6]],
[[ 7, 10],
[ 8, 11],
[ 9, 12]]])
>>> np.moveaxis(A, 2, 1)
array([[[ 1, 4],
[ 2, 5],
[ 3, 6]],
[[ 7, 10],
[ 8, 11],
[ 9, 12]]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With