Zero Pad Ndarray Along Axis
I want to pad: [[1, 2] [3, 4]] to [[0, 0, 0] [0, 1, 2] [0, 3, 4]] I have no problem in doing so when input is 2D by vstack & hsrack However, when I add 1 dim to represent
Solution 1:
You can use np.pad
, which allows you to specify the number of values padded to the edges of each axis.
So for the first example 2D
array you could do:
a = np.array([[1, 2],[3, 4]])
np.pad(a,((1, 0), (1, 0)), mode = 'constant')
array([[0, 0, 0],
[0, 1, 2],
[0, 3, 4]])
So here each tuple is representing the side which to pad with zeros along each axis, i.e. ((before_1, after_1), … (before_N, after_N))
.
And for a 3D
array the same applies, but in this case we must specify that we only want to zero
pad the two last dimensions:
img = np.random.randint(-10, 10, size=(2, 2, 2))
np.pad(img, ((0,0), (1,0), (1,0)), 'constant')
array([[[ 0, 0, 0],
[ 0, -3, -2],
[ 0, 9, -5]],
[[ 0, 0, 0],
[ 0, 1, -9],
[ 0, -1, -3]]])
Solution 2:
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)
Output:
[[0 0 0]
[0 1 2]
[0 3 4]]
Post a Comment for "Zero Pad Ndarray Along Axis"