I have a numpy
array with shape (1, 79, 161)
. I need to make the shape (1, 100, 161)
by padding the center axis with zeroes to the right. What's the best way to accomplish this?
Asked
Active
Viewed 1,037 times
-2

Shamoon
- 41,293
- 91
- 306
- 570
-
2Have you seen [`numpy.pad`](https://numpy.org/devdocs/reference/generated/numpy.pad.html)? – Warren Weckesser Feb 22 '20 at 18:48
-
I have - but am unsure how to use it – Shamoon Feb 22 '20 at 18:49
-
1Does this answer your question? [python how to pad numpy array with zeros](https://stackoverflow.com/questions/35751306/python-how-to-pad-numpy-array-with-zeros) – AMC Feb 22 '20 at 19:24
2 Answers
1
Here is a generic approach using np.pad
. The trick is to get the pad_width
argument right. In your original question, the correct pad_width
would be [(0, 0), (0, 21), (0, 0)]
. Each pair of numbers is the padding before the axis and then after the axis. You want to right pad the second dimension, so the pair should be (0, 21)
. The methods below calculate the correct pad width argument based on shape of the original array and the desired array shape.
import numpy as np
orig_shape = (1, 79, 161)
new_shape = (1, 100, 161)
pad_width = [(0, j - i) for i, j in zip(orig_shape, new_shape)]
# pad_width = [(0, 0), (0, 21), (0, 0)]
orig_array = np.random.rand(*orig_shape)
padded = np.pad(orig_array, pad_width)
Another option: you can create a new numpy array of zeros, and then fill it in with your existing values.
import numpy as np
x = np.zeros((1, 100, 161))
x[:, :79, :] = OLD_ARRAY

jkr
- 17,119
- 2
- 42
- 68
-
-
-
In this case, it's `79`. But for other instances, it might be a different number – Shamoon Feb 22 '20 at 18:56
1
Use numpy.pad
:
>>> x = np.ones((1,79,161))
>>> x
array([[[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
...,
[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.]]])
>>> y = np.pad(x, ((0,0), (0,1), (0, 0)))
>>> y
array([[[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
...,
[1., 1., 1., ..., 1., 1., 1.],
[1., 1., 1., ..., 1., 1., 1.],
[0., 0., 0., ..., 0., 0., 0.]]])
>>> y.shape
(1, 80, 161)
>>> z = np.pad(x, ((0,0), (0,21), (0, 0)))
>>> z.shape
(1, 100, 161)
The tuples signify padding_width
before and after for each dimension.

Sayandip Dutta
- 15,602
- 4
- 23
- 52