【问题标题】:numpy: concatenate two arrays along the 3rd dimensionnumpy:沿第三维连接两个数组
【发布时间】:2018-07-20 09:37:03
【问题描述】:

我想向现有数据立方体添加另一个“切片”数据:

import numpy as np

a = np.array([[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]], [[4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6]]])
print(a.shape)  # (2, 3, 4)

b = np.array([[7, 7, 7], [8, 8, 8]])
print(b.shape)  # (2, 3)

c = np.concatenate([a, b], axis=2)  # ValueError: all the input arrays must have same number of dimensions 
print(c.shape)  # wanted result: (2, 3, 5)

所以我基本上想通过将最后一个维度扩展到 2x3x5 来将 2x3 数组添加到 2x3x4 数组中。值错误对我来说不太有意义,因为数组不能是相同的形状?我在这里做错了什么?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    在b的末尾添加一个新轴,然后连接-

    np.concatenate((a, b[...,None]), axis=2)
    

    所以,对于给定的样本 -

    In [95]: np.concatenate((a, b[...,None]), axis=2).shape
    Out[95]: (2, 3, 5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-25
      • 2012-03-03
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-02
      相关资源
      最近更新 更多