48

If I run the following:

import numpy as np
a = np.arange(9)
a = a.reshape((3,3))

I will get this:

a = [[0 1 2]
     [3 4 5]
     [6 7 8]]

If I create a larger array like this:

b = np.zeros((5,5))
b = [[ 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.]]

How do I efficiently copy a into b to get an array like this?

# border of 0 surrounding a to be filled in with other data later
b = [[ 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.]]

I am looking for a function built into numpy if it exists.

2 Answers 2

56

You can specify b[1:4, 1:4] to denote the part:

>>> import numpy as np
>>> a = np.arange(9)
>>> a = a.reshape((3, 3))
>>> b = np.zeros((5, 5))
>>> b[1:4, 1:4] = a
>>> b
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.]])

>>> b[1:4,1:4] = a + 1  # If you really meant `[1, 2, ..., 9]`
>>> b
array([[ 0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  2.,  3.,  0.],
       [ 0.,  4.,  5.,  6.,  0.],
       [ 0.,  7.,  8.,  9.,  0.],
       [ 0.,  0.,  0.,  0.,  0.]])
Sign up to request clarification or add additional context in comments.

Comments

10

Just as an alternative, should you want a different pad value other than zero, you can use this option

>>> a = np.arange(9.).reshape(3,3)
>>> np.pad(a, 1, 'constant', constant_values=0)
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.]])
>>> np.pad(a, 1, 'constant', constant_values=5)
array([[ 5.,  5.,  5.,  5.,  5.],
       [ 5.,  0.,  1.,  2.,  5.],
       [ 5.,  3.,  4.,  5.,  5.],
       [ 5.,  6.,  7.,  8.,  5.],
       [ 5.,  5.,  5.,  5.,  5.]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.