简体   繁体   English

在具有(a,b,c)形状的 numpy 数组的元素之间添加零

[英]Adding zeros in between elements in numpy array with (a,b,c) shape

I have a numpy array like this我有一个这样的 numpy 数组

array([[[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]],

       [[1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.],
        [1., 1., 1., 1., 1.]]])

shape = (2, 3, 5)形状 = (2, 3, 5)

And I want an output which looks like this我想要一个 output 看起来像这样

output = array([[[1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.],
         [1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.],
         [1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.]],

        [[1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.],
         [1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.],
         [1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.]]])

Note: The number of zeros to be inserted can vary depending on given factor, in this case the factor was k=3, and the insert is (k-1) which means two zeros will be inserted between numbers.注意:要插入的零的数量可以根据给定的因子而变化,在这种情况下,因子是 k=3,插入是 (k-1),这意味着将在数字之间插入两个零。 Also given this output I would like to get to the initial input还给出了这个 output 我想获得初始输入

You can use numpy.zeros to initialize an output array of the desired shape, then indexing to fill the values:您可以使用numpy.zeros初始化所需形状的output数组,然后索引以填充值:

k = 3
shape = a.shape
output = np.zeros(shape[:-1]+((shape[-1]-1)*k+1,))

output[...,::k] = a

output: output:

array([[[1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.],
        [1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.],
        [1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.]],

       [[1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.],
        [1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.],
        [1., 0., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0., 1.]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM