【问题标题】:Repeat/duplicate a given numpy array ten times重复/复制给定的 numpy 数组十次
【发布时间】:2019-01-10 05:15:14
【问题描述】:

我有一个形状为 (320, 320, 3) 的 numpy array。我想重复/复制此数据 10 次,并希望获得新的形状数组 (10, 320, 320, 3)。

怎么做?

array = np.ones((320, 320, 3))
print (array.shape)
(320, 320, 3)

我试过了:

res = np.tile(array, 10)
print (res.shape)

(320, 320, 30).

但我想要shape的,

(10, 320, 320, 3)

【问题讨论】:

    标签: python arrays numpy scipy


    【解决方案1】:

    我们可以使用np.broadcast_to -

    np.broadcast_to(a,(10,)+a.shape).copy() # a is input array
    

    如果我们对视图没问题,请跳过 .copy() 以获得几乎免费的运行时和零内存开销。

    我们也可以使用np.repeat -

    np.repeat(a[None],10,axis=0)
    

    【讨论】:

      【解决方案2】:

      您可以使用np.resize,如果新尺寸大于旧尺寸,它将平铺:

      array = np.ones((320, 320, 3))
      
      new_array = np.resize(array, (10, *array.shape))
      print(new_array.shape)
      # (10, 320, 320, 3)
      

      来自the docs

      numpy.resize(a, new_shape): 如果新数组比原来的数组大,那么新数组会被a的重复副本填充。

      【讨论】:

        【解决方案3】:
        res = np.tile(array, (10,1,1,1))
        print (res.shape)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-30
          • 2014-07-04
          • 2016-10-06
          • 1970-01-01
          • 2020-10-15
          • 2023-03-20
          • 2014-10-17
          相关资源
          最近更新 更多