Reputation: 65
How can I add one row and one column to a numpy array. The array has the shape (480,639,3) and I want to have the shape (481,640,3). The new row and column should filled with zeros, like this:
[43,42,40], ... [64,63,61], [0,0,0]
... ... ... [0,0,0]
[29,29,29], ... [38,37,35], [0,0,0]
[0,0,0], [0,0,0] ... [0,0,0]
To add a new column I'm doing this:
b = numpy.zeros((480,640,3), dtype = int)
b[:,:-1] = old_arry
But how I can add one row? Have I to use a loop or exists a better way to do this?
Upvotes: 2
Views: 1293
Reputation: 231665
You can expand both dimensions at once, or you can expand it one dimension at a time. The operation is the same - create the target array, and copy the old to an appropriate slice. pad
does this under the hood.
b = numpy.zeros((481,640,3), dtype = int)
b[:-1,:-1,:] = old_arry
for example:
In [527]: x=np.ones((2,2,3))
In [528]: y=np.zeros((3,3,3))
In [529]: y[:-1,:-1:,:]=x
In [530]: y
Out[530]:
array([[[ 1., 1., 1.],
[ 1., 1., 1.],
[ 0., 0., 0.]],
[[ 1., 1., 1.],
[ 1., 1., 1.],
[ 0., 0., 0.]],
[[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]]])
Upvotes: 0
Reputation: 12713
You can use np.vstack
to stack arrays row-wise and np.hstack
to stack them column-wise. See the code:
>>> import numpy as np
>>> x = np.arange(480*639*3).reshape((480,639,3))
>>> new_row = np.zeros((639,3))
>>> x = np.vstack((x,new_row[np.newaxis,:,:]))
>>> x.shape
(481, 639, 3)
>>> new_col = np.zeros((481,3))
>>> x = np.hstack([x, new_col[:,np.newaxis,:]])
>>> x.shape
(481, 640, 3)
Upvotes: 1
Reputation: 32521
You can use pad
>>> old = np.random.random_integers(0, 100, size=(480, 640))
>>> np.pad(old, pad_width=((0, 1), (0, 1)), mode='constant')
array([[ 66, 22, 51, ..., 18, 15, 0],
[ 28, 12, 43, ..., 8, 38, 0],
[ 55, 43, 89, ..., 67, 58, 0],
...,
[ 17, 25, 100, ..., 12, 52, 0],
[ 97, 59, 82, ..., 38, 97, 0],
[ 0, 0, 0, ..., 0, 0, 0]])
>>> np.pad(old, pad_width=((0, 1), (0, 1)), mode='constant').shape
(481, 641)
>>>
You can also write it as np.pad(old, ((0, 1), (0, 1)), mode='constant')
, i.e. without the pad_width
keyword. To set a different value for the padded areas, see the constant_values
parameter in the documentation.
Upvotes: 3