Numpy:部分转置和堆叠

问题描述

假设我有一个 3 维数组 A

A = np.random.rand(4,4,5)
AT = np.zeros((4,5))

# Firstly I want to transpose the first two dimension of A but keep the third dimension fixed
# that is
a,b,c = A.shape

for i in range(c):
    AT[:,:,i] = A[:,i].T

# then I want to stack the A and AT into a 4 dimension array
# that is
B = zeros((4,2,5))
B[:,:] = A
B[:,1,:] = AT

代码的第一部分有效,但有没有更好的方法来实现它?

对于第二部分,我该如何解决

解决方法

对您的问题 1) swapaxes 和 2) stack 的简短回答:

B = np.stack([A,A.swapaxes(0,1)],axis=2)