简体   繁体   English

python-用1D数组用零填充制作3D数组,具体取决于1D数组的索引

[英]Make 3D array with 1D arrays with zero padding depending on index of 1D array numpythonically

Consider the following 1D arrays 考虑以下一维数组

a=np.arange(3)+9
b=np.arange(3)+5

currently I am initializing the new 3d array by using 目前我正在通过使用初始化新的3d数组

n=4
cols=3
k=np.vstack((a,b,a*b,np.zeros((n,cols)),a,b,a,a,b**2,np.zeros((n,cols)),a*2,a)).T.reshape(-1,2,n+5)

where a and b will always be the same shape 其中a和b总是相同的形状

which results in 导致

array([[[  9.,   5.,  45.,   0.,   0.,   0.,   0.,   9.,   5.],
        [  9.,   9.,  25.,   0.,   0.,   0.,   0.,  18.,   9.]],

       [[ 10.,   6.,  60.,   0.,   0.,   0.,   0.,  10.,   6.],
        [ 10.,  10.,  36.,   0.,   0.,   0.,   0.,  20.,  10.]],

       [[ 11.,   7.,  77.,   0.,   0.,   0.,   0.,  11.,   7.],
        [ 11.,  11.,  49.,   0.,   0.,   0.,   0.,  22.,  11.]]])

How would i use a similar technique, also without a for loop, to change the zero padding to the following: 我将如何使用类似的技术(也没有for循环)将零填充更改为以下内容:

array([[[  9.,   5.,  45.,   9.,   5.,   0.,   0.,   0.,   0.],
        [  9.,   9.,  25.,  18.,   9.,   0.,   0.,   0.,   0.]],

       [[ 10.,   6.,  60.,   0.,   0.,  10.,   6.,   0.,   0.],
        [ 10.,  10.,  36.,   0.,   0.,  20.,  10.,   0.,   0.]],

       [[ 11.,   7.,  77.,   0.,   0.,   0.,   0.,  11.,   7.],
        [ 11.,  11.,  49.,   0.,   0.,   0.,   0.,  22.,  11.]]])

One can use advanced-indexing to assign those array values into a zeros initialized array given the column indices - 在给定列索引的情况下,可以使用advanced-indexing将这些数组值分配为零初始化数组-

out = np.zeros((3,2,9),dtype=bool)
vals = np.array([[a,b,a*b,a,b],[a,a,b**2,2*a,a]])
out[np.arange(3)[:,None],:, idx] = vals.T

Sample run - 样品运行-

In [448]: a
Out[448]: array([ 9, 10, 11])

In [449]: b
Out[449]: array([5, 6, 7])

In [450]: out
Out[450]: 
array([[[  9.,   5.,  45.,   9.,   5.,   0.,   0.,   0.,   0.],
        [  9.,   9.,  25.,  18.,   9.,   0.,   0.,   0.,   0.]],

       [[ 10.,   6.,  60.,   0.,   0.,  10.,   6.,   0.,   0.],
        [ 10.,  10.,  36.,   0.,   0.,  20.,  10.,   0.,   0.]],

       [[ 11.,   7.,  77.,   0.,   0.,   0.,   0.,  11.,   7.],
        [ 11.,  11.,  49.,   0.,   0.,   0.,   0.,  22.,  11.]]])

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

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