numpy.pad(array, pad_width, mode=‘constant’, **kwargs)
使用函数 numpy.pad 介绍:
array:要填充的数组
pad_width:(before,after)简单来说就是前面填几和后面填几,如(2,3)就是前填2后填3
“constant”:默认填常数,可以选择别的
实例;
1.首先对一维的数组进行填充
a = [1,1,1,2,2,2,3,3,3,4,4,4] a = np.pad(a, pad_width = (1,1), mode = 'constant') print(a) [0 1 1 1 2 2 2 3 3 3 4 4 4 0]
在a的左右各添加一个常数,默认常数为0
2.对一维的数组进行前后不一样值的填充
b = [1,1,2,2] b = np.pad(b,(1,1), mode = 'constant', constant_values = (2,4)) print(b) [2 1 1 2 2 4]
前2,后4
3.对2维数组进行扩充
注:numpy.pad的官方指南中用到了“axis”一词表示轴,可以理解为行,0 axis 就是第0行。
d = np.arange(0,10).reshape(2,5) print(d) d = np.pad(d, ((1,1),(2,2)), "constant") #d = np.pad(d, (1,1), "constant") print(d) [[0 1 2 3 4] [5 6 7 8 9]] [[0 0 0 0 0 0 0 0] [0 0 1 2 3 4 0 0] [0 5 6 7 8 9 0 0] [0 0 0 0 0 0 0 0]]



