w3resource logo
Python Exercises

Python NumPy: Add a border around an existing array

Python NumPy: Array Object Exercise-9 with Solution

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

Sample Solution:-

Python Code:

import numpy as np
x = np.ones((3,3))
print("Original array:")
print(x)
print("1 on the border and 0 inside in the array")
x = np.pad(x, pad_width=1, mode='constant', constant_values=0)
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.]]

Python Code Editor:

import numpy as np
x = np.ones((3,3))
print("Original array:")
print(x)
print("1 on the border and 0 inside in the array")
x = np.pad(x, pad_width=1, mode='constant', constant_values=0)
print(x)

Improve this sample solution and post your code through Disqus