w3resource

NumPy: Add a border around an existing array

NumPy: Array Object Exercise-9 with Solution

Write a NumPy program to add a border (filled with 0's) around an existing array.

Python NumPy: Add a border around an existing array

Sample Solution:

Python Code:

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

# Creating a 3x3 NumPy array filled with ones
x = np.ones((3, 3))

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

# Modifying the array 'x' to set 0s on the border and 1s inside the array using the np.pad function
print("0 on the border and 1 inside in the array")
x = np.pad(x, pad_width=1, mode='constant', constant_values=0)

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

Sample Output:

Original array:                                                         
[[ 1.  1.  1.]                                                          
 [ 1.  1.  1.]                                                          
 [ 1.  1.  1.]]                                                         
1 on the border and 0 inside in the array                               
[[ 0.  0.  0.  0.  0.]                                                  
 [ 0.  1.  1.  1.  0.]                                                  
 [ 0.  1.  1.  1.  0.]                                                  
 [ 0.  1.  1.  1.  0.]                                                  
 [ 0.  0.  0.  0.  0.]]

Explanation:

In the above code –

x = np.ones((3,3)): Creates a 3x3 NumPy array filled with ones.

x = np.pad(x, pad_width=1, mode='constant', constant_values=0): The np.pad function is used to pad the input array x with a border of specified width and values. In this case, pad_width=1 adds a border of width 1 around the array. The mode='constant' specifies that the padding should be done with constant values, and constant_values=0 indicates that the constant value for padding should be 0.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a 2d array with 1 on the border and 0 inside.
Next: Write a NumPy program to create a 8x8 matrix and fill it with a checkerboard pattern.

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-9.php