How to pad a 2D numpy array on all four sides with 0.
a = np.array([(1, 2, 3),(4, 5, 6)])
As mentioned, you can use numpy.pad
.
You can use pad_width=1
and mode='constant'
. You can add constant_values=0
, but since 0
is the default value this is not necessary.
import numpy as np
a = np.array([(1, 2, 3),(4, 5, 6)])
res = np.pad(a, pad_width=1, mode='constant')
print(res)
# [[0 0 0 0 0]
# [0 1 2 3 0]
# [0 4 5 6 0]
# [0 0 0 0 0]]