沿轴零填充ndarray [英] Zero pad ndarray along axis

查看:60
本文介绍了沿轴零填充ndarray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要填充:

[[1, 2]
 [3, 4]]

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

当vstack& 2D输入为2D时,我这样做没有问题.hsrack

I have no problem in doing so when input is 2D by vstack & hsrack

但是,当我添加1个dim来代表数字的dim时,例如:

However, when I add 1 dim to represent the dim of number, such as:

img = np.random.randint(-10, 10, size=(2, 2, 2))

如果我不想使用for循环,则无法这样做.有什么方法可以避免,但只有numpy的堆栈可以做到?

ps:在此示例中,我应该通过每2个img实例在第1列&处以零填充来获得(2,3,3)数组.第一行.

ps: for this example I should get (2,3,3) array by each 2 img instance is pad by zero at 1st column & 1st row.

谢谢

推荐答案

您可以使用 np.pad 并删除最后一行/列:

You can use np.pad and remove the last row/column:

import numpy as np

a = np.array([[1, 2], [3, 4]])
result = np.pad(a, 1, mode='constant', constant_values=0)[:-1, :-1]
print(result)

输出:

[[0 0 0]
 [0 1 2]
 [0 3 4]]

这篇关于沿轴零填充ndarray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆