w3resource

NumPy: Create a 2d array with 1 on the border and 0 inside


2D Array (Border 1, Inside 0)

Write a NumPy program to create a 2D array with 1 on the border and 0 inside.

Python NumPy: Create a 2d array with 1 on the border and 0 inside

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 5x5 NumPy array filled with ones
x = np.ones((5, 5))

# Printing the original array 'x'
print("Original array:")
print(x)

# Modifying the array 'x' to set the border elements to 1 and inner elements to 0
print("1 on the border and 0 inside in the array")
x[1:-1, 1:-1] = 0

# Printing the modified array 'x' showing 1s on the border and 0s inside
print(x)

Sample Output:

Original 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 on the border and 0 inside in the array                               
[[ 1.  1.  1.  1.  1.]                                                  
 [ 1.  0.  0.  0.  1.]                                                  
 [ 1.  0.  0.  0.  1.]                                                  
 [ 1.  0.  0.  0.  1.]                                                  
 [ 1.  1.  1.  1.  1.]]

Explanation:

In the above code –

x = np.ones((5,5)): Creates a 5x5 NumPy array filled with ones.

x[1:-1,1:-1] = 0: This indexing operation sets the value of the inner elements of the array to zero by slicing the rows and columns from index 1 to the second last index (i.e., excluding the first and last rows and columns). The assignment operation (= 0) sets the selected elements to zero.

Python-Numpy Code Editor: