How to Add a Border Around a NumPy Array
Adding a border around a NumPy array means surrounding the original array with extra rows and columns. NumPy provides the numpy.pad() function, which allows adding borders of any width and value. This is commonly done when preparing matrices for image processing, padding operations, or structural modifications.
Example: This example shows how a border is added around a 2×2 array. A padding width of 1 and a border value of 0 are used to surround the original matrix.
import numpy as np
arr = np.ones((2, 2))
out = np.pad(arr, pad_width=1, mode="constant", constant_values=0)
print(out)
Output
[[0. 0. 0. 0.] [0. 1. 1. 0.] [0. 1. 1. 0.] [0. 0. 0. 0.]]
Explanation:
- np.ones((2, 2)) creates the original 2×2 array.
- np.pad(arr, pad_width=1) adds one layer of padding around all sides.
- mode="constant", constant_values=0 fills the border with 0.
Syntax
numpy.pad(array, pad_width, mode='constant', constant_values=value)
Parameters:
- array: Input NumPy array.
- pad_width: Number of values added to each side.
- mode: Padding type; use "constant" for fixed values.
- constant_values: Value used to pad when mode is "constant".
Examples
Example 1: This example adds a border of -1 around a 4×1 column vector.
import numpy as np
arr = np.array([[10],
[20],
[30],
[40]])
out = np.pad(arr, pad_width=1, mode="constant", constant_values=-1)
print(out)
Output
[[-1 -1 -1] [-1 10 -1] [-1 20 -1] [-1 30 -1] [-1 40 -1] [-1 -1 -1]]
Explanation:
- pad_width=1 adds border on all four sides.
- constant_values=-1 fills border with -1.
Example 2: This example pads a rectangular (3×5) array by adding a border of -1 on all sides.
import numpy as np
arr = np.ones((3, 5))
out = np.pad(arr, pad_width=1, mode="constant", constant_values=-1)
print(out)
Output
[[-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. 1. -1.] [-1. -1. -1. -1. -1. -1. -1.]]
Explanation
- pad_width=1 adds one layer around the array.
- constant_values=-1 fills the border with -1.
Example 3: This example pads only the top and bottom of an array by using different padding widths for each side.
import numpy as np
arr = np.arange(6).reshape(2, 3)
out = np.pad(arr, pad_width=((1, 1), (0, 0)), mode="constant", constant_values=9)
print(out)
Output
[[9 9 9] [0 1 2] [3 4 5] [9 9 9]]
Explanation:
- pad_width=((1, 1), (0, 0)) adds 1 row at top and bottom, no padding on columns.
- constant_values=9 border rows filled with 9.