-2

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?

Shamoon
  • 41,293
  • 91
  • 306
  • 570

2 Answers2

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
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