Reputation: 1461
There is a simple example.
I have a 2d array
a=np.arange(4).reshape(2,2)+1
array([[1, 2],
[3, 4]])
and I wanna insert 0 (or any other value) in the beginning and end of the array, then it becomes
array([[ 0., 0., 0., 0.],
[ 0., 1., 2., 0.],
[ 0., 3., 4., 0.],
[ 0., 0., 0., 0.]])
I'm trying np.insert or np.concatenate, but I failed for >2 dimension. What is the fastest way to handle this kind of problem?
Upvotes: 0
Views: 40
Reputation: 11496
Use numpy.pad
:
>>> np.pad(a, 1, 'constant')
array([[0, 0, 0, 0],
[0, 1, 2, 0],
[0, 3, 4, 0],
[0, 0, 0, 0]])
Upvotes: 1