How to add a border around a NumPy array?

How to add a border around a NumPy array?

To add a border around a NumPy array, you can use the numpy.pad function, which pads an array with a constant value or with other padding methods. Here's how you can do it:

import numpy as np # Example array array = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]) # Add a border with a constant value border_width = 1 # This is the thickness of the border border_value = 0 # This is the value of the border # Create a new array with the border array_with_border = np.pad(array, pad_width=border_width, mode='constant', constant_values=border_value) print(array_with_border) 

The resulting array_with_border will look like this:

[[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]] 

Here, pad_width specifies the number of rows/columns to add at the edges of each axis, mode specifies the padding strategy, and constant_values is the value to set the padding elements if mode='constant'.

The pad_width argument can also take a tuple of tuples to specify different padding widths for different axes and edges:

# Pad with a variable border width and value pad_width = ((1, 2), (3, 4)) # (top, bottom), (left, right) pad_value = 9 array_with_variable_border = np.pad(array, pad_width=pad_width, mode='constant', constant_values=pad_value) print(array_with_variable_border) 

This will produce a NumPy array padded with 9s, with 1 row of padding added to the top, 2 rows to the bottom, 3 columns to the left, and 4 columns to the right.


More Tags

ps poker mapi asp.net-mvc-partialview django-migrations sections findby spark-excel rotativa exoplayer

More Programming Guides

Other Guides

More Programming Examples