Ite*_*tor 8 python arrays numpy
我有一个nd数组,例如:
x = np.array([[1,2,3],[4,5,6]])
Run Code Online (Sandbox Code Playgroud)
我想将最后一个维度的大小加倍,并在元素之间插入零以填充空间.结果应如下所示:
[[1,0,2,0,3,0],[4,0,5,0,6,0]]
Run Code Online (Sandbox Code Playgroud)
我尝试使用expand_dims和解决它pad.但该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]
Run Code Online (Sandbox Code Playgroud)
我的代码结果:
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]])
Run Code Online (Sandbox Code Playgroud)
如何pad在每个元素之后的最后一个维度中插入零?或者有更好的方法来解决这个问题吗?
只需初始化输出数组并指定slicing-
m,n = x.shape
out = np.zeros((m,2*n),dtype=x.dtype)
out[:,::2] = x
Run Code Online (Sandbox Code Playgroud)
或者堆叠 -
np.dstack((x,np.zeros_like(x))).reshape(x.shape[0],-1)
Run Code Online (Sandbox Code Playgroud)
您可以简单地使用插入功能来做到这一点:
np.insert(x, [1,2,3], 0, axis=1)
array([[1, 0, 2, 0, 3, 0],
[4, 0, 5, 0, 6, 0]])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4082 次 |
| 最近记录: |