【问题标题】:Numpy concatenating along a new dimensionNumpy 沿新维度连接
【发布时间】:2019-07-03 21:07:41
【问题描述】:

我正在尝试做这个人正在做的事情numpy: extending arrays along a new axis?,但我不想在新维度中重复相同的数组。我正在生成一个新的 2D 数组,并希望将其附加到第 3 维

我尝试过使用 np.stack((a,b), axis=2) 但数组的形状必须相同。所以在它堆叠前两个数组之后,第二次迭代的形状是 (256, 256, 2) 和 (256, 256) 我得到 ValueError: all input arrays must have the same shape

a = something #a has shape (256, 256)
for i in np.arange(0,10):
    #calculate b and it also has shape (256,256)
    a = np.stack((a,b), axis=2)
print(a.shape) #should give (256, 256, 10)

【问题讨论】:

    标签: numpy-ndarray


    【解决方案1】:

    您也可以通过将数组存储在列表中并使用np.stack 来做到这一点。也许效率不高,但我发现它更容易阅读。

    import numpy as np
    
    a = np.random.rand(256, 256)  # array with shape (256, 256)
    
    c = [a] # put initial array into a list
    for i in np.arange(10):
        b = np.random.rand(256, 256)  # b is also array with shape (256, 256)
        c.append(b) # append each new array to the list
    
    # convert the list of arrays to 3D array
    final = np.stack(c, axis=2)  # axis argument specifies which axis to stack along
    
    

    【讨论】:

      【解决方案2】:

      你想连接你的数组,但是沿着一个新的第三维。要使数组维度一致,您可以在索引它们时使用 None 。按照上面的例子,这看起来像:

      import numpy as np
      
      a = np.random.rand(256, 256) # something with shape (256, 256)
      
      c = a[ :, :, None] # start out by copying a into c but add in an extra dimension using None
      
      for i in np.arange(10):
          b = np.random.rand(256, 256) # b is also something with shape (256, 256)
          c = np.concatenate((c, b[ :, :, None]), axis=2) # concatenate it to c, again using None to add in the extra dimension to b, and joining along the new axis.
      
      c.shape # will be (256,256,11) for each of the ten iterations plus the initial copying of a into c.
      

      【讨论】:

        猜你喜欢
        • 2013-11-07
        • 2018-05-31
        • 1970-01-01
        • 2020-08-02
        • 1970-01-01
        • 1970-01-01
        • 2013-10-17
        • 1970-01-01
        • 2018-05-12
        相关资源
        最近更新 更多