Home > Mobile >  Python Numpy: How to transpose only the last several dimensions
Python Numpy: How to transpose only the last several dimensions

Time:09-17

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.

CodePudding user response:

The np.moveaxis method is what you want:

a = np.moveaxis(a, -1, -2)
  • Related