【问题标题】:Reshape 5D array to 2D array将 5D 数组重塑为 2D 数组
【发布时间】:2021-10-11 09:56:23
【问题描述】:

我有一个具有这种形状 (26, 396, 1, 1, 6) 的数组,我想将其转换成这种形状 (10296, 6),这意味着我想将 396 个数组堆叠在一起。

我试过了:

a = b.reshape(26*396,6)

但这并不能正确“堆叠”它们。我希望 (1, 396, 1, 1, 6) 成为新数组的前 396 个数组, (2, 396, 1, 1, 6) 成为数组的下一个 396 个数组, (3, 396, 1, 1, 6) 下一个,依此类推。

【问题讨论】:

标签: numpy reshape


【解决方案1】:

我相信您正在寻找的是使用np.concatenate 向下连接第二个轴:

>>> np.concatenate(x, 1).reshape(-1, 6)

或者,您可以使用np.hstack

>>> np.hstack(x).reshape(-1, 6)

或者,如 cmets 中的 @Yann Ziselman 所述,您可以在重塑为最终形式之前交换前两个轴:

x.swapaxes(0,1).reshape(-1, 6)

这是一个最小的例子:

>>> x = np.random.rand(3, 4, 1, 1, 3)
array([[[[[0.66762863, 0.67280411, 0.8053661 ]]],


        [[[0.55051478, 0.79648146, 0.66660467]]]],



       [[[[0.58070253, 0.76738551, 0.30835528]]],


        [[[0.10904043, 0.13234366, 0.25146988]]]]])


>>> np.hstack(x).reshape(-1, 3)
array([[0.66762863, 0.67280411, 0.8053661 ],
       [0.58070253, 0.76738551, 0.30835528],
       [0.55051478, 0.79648146, 0.66660467],
       [0.10904043, 0.13234366, 0.25146988]])

>>> np.reshape(-1, 3) # compared to flattening operation
array([[0.66762863, 0.67280411, 0.8053661 ],
       [0.55051478, 0.79648146, 0.66660467],
       [0.58070253, 0.76738551, 0.30835528],
       [0.10904043, 0.13234366, 0.25146988]])

【讨论】:

  • 这给了我:a= np.concatenate(stress_tensors_to_append.view(-1,6)) ValueError: Type must be a sub-type of ndarray type
  • @AsbjoernLund 使用np.reshape 而不是np.view
  • @Ivan 你的回答和 OP 应该做的有什么区别?它看起来完全一样,但是您使用的代码更多,因此效率更低。
  • @Ivan 会不会和 a = b.transpose(1, 0, 2, 3, 4).reshape(-1, 6) 一样?
  • @yannziselman 确实会。实际上,您可以使用np.swapaxes: x.swapaxes(0,1).reshape(-1, 6)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 2018-05-12
相关资源
最近更新 更多