微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Numpy:部分转置和堆叠

如何解决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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。