Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Numpy: How to transpose only the last several dimensions

Tags:

python

numpy

For example, if I only want to transpose the last two dimensions of this array: a=np.random.randn(2,2,2,2,2), I would write something like: a.transpose((0,1,2,4,3)). How do I omit the leading dimensions? What are the neat and efficient methods? Thanks!

Edit, I know how to simply swap the shape and strides of the array, but I think it looks messy:

strides=list(a.strides)
strides[-2], strides[-1]=strides[-1], strides[-2]
a.strides= strides

shape=list(a.shape)
shape[-2], shape[-1]=shape[-1], shape[-2]
a.shape= shape

I'm wondering if there is a neat way of doing it.

like image 201
Sam-gege Avatar asked Oct 29 '25 06:10

Sam-gege


1 Answers

The np.moveaxis method is what you want:

a = np.moveaxis(a, -1, -2)
like image 183
Tevien Avatar answered Oct 31 '25 12:10

Tevien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!