【问题标题】:How to insert zeros between elements in a numpy array?如何在numpy数组的元素之间插入零?
【发布时间】:2017-11-05 19:46:09
【问题描述】:

我有一个 nd 数组,例如这个:

x = np.array([[1,2,3],[4,5,6]])

我想将最后一个维度的大小加倍,并在元素之间插入零以填充空间。结果应如下所示:

[[1,0,2,0,3,0],[4,0,5,0,6,0]]

我尝试使用expand_dimspad 解决它。但是pad 函数不仅仅在最后一个维度中的每个值之后插入零。结果的形状是(3, 4, 2),但应该是(2,3,2)

y = np.expand_dims(x,-1)
z = np.pad(y, (0,1), 'constant', constant_values=0)
res = np.reshape(z,[-1,2*3]

我的代码结果:

array([[1, 0, 2, 0, 3, 0],
       [0, 0, 4, 0, 5, 0],
       [6, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0]])

pad 如何在每个元素之后的最后一个维度中插入零?或者有没有更好的方法来解决这个问题?

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    只需初始化输出数组并使用slicing进行赋值 -

    m,n = x.shape
    out = np.zeros((m,2*n),dtype=x.dtype)
    out[:,::2] = x
    

    或者堆叠 -

    np.dstack((x,np.zeros_like(x))).reshape(x.shape[0],-1)
    

    【讨论】:

    • 啊,我只是在写“可能有一个聪明的方法可以做到这一点,但我们是 Python 程序员,所以我们正式不赞成聪明。我只是构建目标数组并插入原来的一个,”那是我看到你发帖的时候。 ;-)
    【解决方案2】:

    您可以使用insert 函数简单地做到这一点:

    np.insert(x, [1,2,3], 0, axis=1)
    
    array([[1, 0, 2, 0, 3, 0],
           [4, 0, 5, 0, 6, 0]])
    

    【讨论】:

      【解决方案3】:

      根据您的 expand_dims,我们可以使用stack

      In [742]: x=np.arange(1,7).reshape(2,-1)
      In [743]: x
      Out[743]: 
      array([[1, 2, 3],
             [4, 5, 6]])
      In [744]: np.stack([x,x*0],axis=-1).reshape(2,-1)
      Out[744]: 
      array([[1, 0, 2, 0, 3, 0],
             [4, 0, 5, 0, 6, 0]])
      

      stack 使用expend_dims 添加维度;就像np.array,但可以更好地控制新轴的添加方式。因此,这是一种散布数组的便捷方式。

      堆栈产生一个 (2,4,2) 数组,我们将其整形为 (2,8)。

      x*0 可以替换为 np.zeros_like(x),或者任何创建相同大小的零数组的东西。

      np.stack([x,x*0],axis=1).reshape(4,-1) 添加 0 行。

      【讨论】:

        【解决方案4】:

        你需要pad only one side的新维度:

        x = np.array( [[1,2,3],[4,5,6]] )
        y = np.expand_dims(x,-1)
        z = np.pad( y, ((0, 0), (0, 0), (0, 1)) , 'constant', constant_values=0)
        res = np.reshape(z, ( x.shape[0] , 2*x.shape[1] ) )
                         
        res
        
        array([[1, 0, 2, 0, 3, 0],
               [4, 0, 5, 0, 6, 0]])
        

        【讨论】: