如何在numpy数组的元素之间插入零? [英] How to insert zeros between elements in a numpy array?
问题描述
我有一个nd数组,例如:
I have an nd array, for example this:
x = np.array([[1,2,3],[4,5,6]])
我想将最后一个尺寸的大小加倍,并在元素之间插入零以填充空间.结果应如下所示:
I would like to double the size of the last dimension, and insert zeroes between the elements to fill the space. The result should look like this:
[[1,0,2,0,3,0],[4,0,5,0,6,0]]
我试图使用expand_dims
和pad
解决它.但是pad
函数不仅在最后一个维度中的每个值之后插入零.结果的形状为(3, 4, 2)
,但应为(2,3,2)
I tried to solve it using expand_dims
and pad
. But the pad
function inserts zeroes not just after each value in the last dimension. The shape of it's result is (3, 4, 2)
, but it should be (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
如何在每个元素之后的最后一个维度中插入零?还是有解决这个问题的更好方法?
How is it possible with pad
to insert zeroes in the last dimension after each element? Or is there any better way to solve the problem?
推荐答案
简单地初始化输出数组并使用slicing
-
Simply initialize output array and assign with 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)
这篇关于如何在numpy数组的元素之间插入零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!