Write a NumPy program to add a border (filled with 0’s) around an existing array. Return the array with the border.
Example 1:
Input: np.ones((3,3)) Output: 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.]])
Example 2:
Input: np.full((3,3), 2) Output: array([[0., 0., 0., 0., 0.], [0., 2., 2., 2., 0.], [0., 2., 2., 2., 0.], [0., 2., 2., 2., 0.], [0., 0., 0., 0., 0.]])
You can use np.pad() function to add a border around an existing array.
import numpy as np def add_border(array): return np.pad(array, pad_width=1, mode='constant', constant_values=0) print(add_border(np.ones((3,3)))) print(add_border(np.full((3,3), 2)))
Unlock AI & Data Science treasures. Log in!