I have a 3-D ndarray.
>>> b = np.arange(27).reshape(3,3,3)
>>> b
array([[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]]])
Numpy pad function returns a 5x5x5 array:
>>> np.pad(b, (1, 1), constant_values=0)
array([[[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 0, 1, 2, 0],
[ 0, 3, 4, 5, 0],
[ 0, 6, 7, 8, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 9, 10, 11, 0],
[ 0, 12, 13, 14, 0],
[ 0, 15, 16, 17, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 18, 19, 20, 0],
[ 0, 21, 22, 23, 0],
[ 0, 24, 25, 26, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0]]])
However, I want a 5x5x3 array like this:
array([[[ 0, 0, 0, 0, 0],
[ 0, 0, 1, 2, 0],
[ 0, 3, 4, 5, 0],
[ 0, 6, 7, 8, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 9, 10, 11, 0],
[ 0, 12, 13, 14, 0],
[ 0, 15, 16, 17, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 18, 19, 20, 0],
[ 0, 21, 22, 23, 0],
[ 0, 24, 25, 26, 0],
[ 0, 0, 0, 0, 0]]])
How do I achieve the above?
CodePudding user response:
You can either use ((0,0),(1,1),(1,1))
to pad instead of (1,1)
:
np.pad(b, ((0,0),(1,1),(1,1)), constant_values=0)
...or just trim off the first and last items:
np.pad(b, (1,1), constant_values=0)[1:-1]
CodePudding user response:
Might not be the most elegant solution but:
>>> np.pad(b, (1,1), constant_values=0)[1:-1]
array([[[ 0, 0, 0, 0, 0],
[ 0, 0, 1, 2, 0],
[ 0, 3, 4, 5, 0],
[ 0, 6, 7, 8, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 9, 10, 11, 0],
[ 0, 12, 13, 14, 0],
[ 0, 15, 16, 17, 0],
[ 0, 0, 0, 0, 0]],
[[ 0, 0, 0, 0, 0],
[ 0, 18, 19, 20, 0],
[ 0, 21, 22, 23, 0],
[ 0, 24, 25, 26, 0],
[ 0, 0, 0, 0, 0]]])
Works for me.