简体   繁体   English

用零填充1D NumPy数组以形成2D数组

[英]Padding 1D NumPy array with zeros to form 2D array

I have a numpy array: 我有一个numpy数组:

arr=np.array([0,1,0,0.5])

I need to form a new array from it as follows, such that every zero elements is repeated thrice and every non-zero element has 2 preceding zeroes, followed by the non-zero number. 我需要按如下方式从中形成一个新数组,这样每个零元素重复三次,每个非零元素都有2个前置零,后跟非零数字。 In short, every element is repeated thrice, zero as it is and non-zero has 2 preceding 0 and then the number itself. 简而言之,每个元素重复三次,原样为零,非零有前面的0,然后是数字本身。 It is as follows: 它如下:

([0,1,0,0.5])=0,0,0, [for index 0]
              0,0,1 [for index 1]
              0,0,0 [for index 2, which again has a zero] and
              0,0,0.5

final output should be: 最终输出应该是:

new_arr=[0,0,0,0,0,1,0,0,0,0,0,0.5]

np.repeat() repeats all the array elements n number of times, but i dont want that exactly. np.repeat()重复所有数组元素n次,但我不想要那样。 How should this be done? 该怎么做? Thanks for the help. 谢谢您的帮助。

A quick reshape followed by a call to np.pad will do it: 快速重新调整,然后调用np.pad就可以了:

np.pad(arr.reshape(-1, 1), ((0, 0), (2, 0)), 'constant')

Output: 输出:

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

You'll want to flatten it back again. 你会想再把它弄平。 That's simply done by calling .reshape(-1, ) . 这只是通过调用.reshape(-1, )

>>> np.pad(arr.reshape(-1, 1), ((0, 0), (2, 0)), 'constant').reshape(-1, )
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
    0.5])

A variant on the pad idea is to concatenate a 2d array of zeros pad理念的一个变体是连接一个2d的零数组

In [477]: arr=np.array([0,1,0,0.5])
In [478]: np.column_stack([np.zeros((len(arr),2)),arr])
Out[478]: 
array([[ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  1. ],
       [ 0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0.5]])
In [479]: _.ravel()
Out[479]: 
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0.5])

or padding in the other direction: 或在另一个方向填充:

In [481]: np.vstack([np.zeros((2,len(arr))),arr])
Out[481]: 
array([[ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  0. ,  0. ,  0. ],
       [ 0. ,  1. ,  0. ,  0.5]])
In [482]: _.T.ravel()
Out[482]: 
array([ 0. ,  0. ,  0. ,  0. ,  0. ,  1. ,  0. ,  0. ,  0. ,  0. ,  0. ,
        0.5])

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

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