【发布时间】:2022-01-17 12:25:47
【问题描述】:
我在np.transpose 中遇到了这种奇怪的行为,其中在numpy 数组和从列表构造的数组上使用时它的工作方式不同。作为一个 MWE,下面的代码被呈现出来。
import numpy as np
a = np.random.randint(0, 5, (1, 2, 3))
print(a.shape)
# prints (1, 2, 3)
b = np.transpose(a, (0, 2, 1))
print(b.shape)
# prints (1, 3, 2), which is expected
# Constructing array from list of arrays
c = np.array([np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3))])
print(c.shape)
# prints (4, 2, 3)
d = np.transpose(c, (2, 0, 1))
print(d.shape)
# prints (3, 4, 2), whereas I expect it to be (2, 3, 4)
我不理解这种行为。为什么从列表构造的数组的维度混淆了?任何帮助表示赞赏。
【问题讨论】:
-
我在您的示例中看不到任何意外行为。
transpose按给定顺序排列轴。为什么你认为这取决于数组的构造? -
@MichaelSzczesny,我的印象是,映射工作相反。在第二个示例中,结果数组中的最后一个维度应该是 4,对应于
(2, 0, 1)的第一个维度应该是 2,第二个维度应该是 3。但正如下面的答案所指出的,映射最初是固定的,然后是我现在理解的排列。
标签: python arrays python-3.x numpy transpose