gpt4 book ai didi

python - 如何在 numpy 数组的元素之间插入零?

转载 作者:太空狗 更新时间:2023-10-29 21:30:33 24 4
gpt4 key购买 nike

我有一个 nd 数组,例如:

x = np.array([[1,2,3],[4,5,6]])

我想将最后一个维度的大小加倍,并在元素之间插入零以填充空间。结果应如下所示:

[[1,0,2,0,3,0],[4,0,5,0,6,0]]

我尝试使用 expand_dimspad 来解决它。但是 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]

我的代码的结果:

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 如何在每个元素后的最后一个维度中插入零?或者有什么更好的方法来解决这个问题?

最佳答案

简单地初始化输出数组并使用切片赋值-

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)

关于python - 如何在 numpy 数组的元素之间插入零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47125884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com