w3resource

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

NumPy: Array Object Exercise-8 with Solution

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:

Previous: Write a NumPy program to an array converted to a float type.
Next: Write a NumPy program to add a border (filled with 0's) around an existing array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/python-numpy-exercise-8.php