8

I am to create an array using only NumPy tools. There it is:

[[2 2 2 2 2]
 [2 1 1 1 2]
 [2 1 1 1 2]
 [2 1 1 1 2]
 [2 2 2 2 2]]

That is my code:

import numpy as np
x = np.ones((5, 5), dtype = int)
x[0, :] = 2
x[4, :] = 2
x[:, 0] = 2
x[:, 4] = 2
print(x)

I wonder if it is possible to create an array like this in an easier (shorter) way?

3 Answers 3

9

Approach #1

Initialize with 2s (edge values) and assign 1s in middle portion -

x = 2*np.ones((5, 5), dtype = int)
x[1:-1,1:-1] = 1

Approach #2

Another short way -

x = np.ones((5, 5), dtype = int)
x[:,[0,-1]] = x[[0,-1]] = 2

Approach #3

One-liner with 2D convolution -

In [302]: from scipy.signal import convolve2d

In [303]: (convolve2d(np.ones((5,5)), np.ones((3,3)),'same')<9)+1
Out[303]: 
array([[2, 2, 2, 2, 2],
       [2, 1, 1, 1, 2],
       [2, 1, 1, 1, 2],
       [2, 1, 1, 1, 2],
       [2, 2, 2, 2, 2]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That will definitely help :)
8
import numpy as np

a = np.ones((5, 5))
b = np.pad(a[1:-1,1:-1], pad_width=((1, 1), (1, 1)), mode='constant', 
constant_values=2)
print b

Comments

4
x = numpy.full((5,5), 2, dtype=int)
x[1:-1,1:-1] = 1

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.