简体   繁体   English

转置3-D Numpy数组

[英]Transposing a 3-d numpy array

Suppose I have a numpy array A with shape (5,24,1) . 假设我有一个形状为(5,24,1)numpy数组A
I want to take five separate transposes along axis = 0 , such that the resulting shape after transposes is (5,1,24) . 我想沿axis = 0进行五个单独的转置,这样转置后的最终形状为(5,1,24)
How can I do this using some of the numpy functions? 如何使用一些numpy函数执行此操作?

Three approaches could be suggested - 可以提出三种方法-

A.swapaxes(1,2)
A.transpose(0,2,1)
np.rollaxis(A,2,1)

For swapaxes and transpose , please follow their docs. 对于swapaxestranspose ,请遵循其文档。

With np.rollaxis , we are rolling the axes to bring the third axis into the second position and thus pushing back the second axis into third axis position. 使用np.rollaxis ,我们将滚动轴以将第三轴移至第二位置,从而将第二轴推回第三轴位置。 More info in the linked docs. 链接文档中的更多信息。

Using the fact that the last axis is singleton - 利用最后一个轴为单例的事实-

A[:,None,:,0]

You could use np.moveaxis (one option missing from Divakars excellent answer) where you can define which axis should be moved: 您可以使用np.moveaxis (Divakars最佳答案中缺少的一个选项),您可以在其中定义应移动的轴:

np.moveaxis(A, (0, 1, 2), (0, 2, 1))

This moves axis 0 to 0 (no change, could also be omitted), 1 to 2 and 2 to 1 . 这会将轴0移动到0 (不变,也可以省略), 1221 So this basically just swaps axis 1 and 2. 因此,这基本上只是交换轴1和2。

>>> A = np.ones((5,24,1))
>>> res = np.moveaxis(A, (1, 2), (2, 1))   # this time without the zeros
>>> res.shape
(5, 1, 24)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM