w3resource

NumPy: Add a border around an existing array


Add Border to Array (0s)

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.


For more Practice: Solve these Related Problems:

  • Pad a given 2D array with a border of zeros using np.pad and verify the new dimensions.
  • Create a function that adds a customizable border around any input array.
  • Append a zero border to an array and then check that the original data remains unchanged.
  • Compare different padding modes to add a border of zeros around a matrix and analyze the outcomes.

Go to:


PREV : 2D Array (Border 1, Inside 0)
NEXT : 8x8 Checkerboard Pattern


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.