NumPy makes it possible to create an array having 1 as border values and 0 inside. To develop this specific kind of array, many ways are available. first, let me show you, how this array looks like and then we look how to develop it.
[[1. 1. 1. 1. 1.], [1. 0. 0. 0. 1.], [1. 0. 0. 0. 1.], [1. 1. 1. 1. 1.]]
1. By "zeros()" function and "Slicing":
zeros()function takes one required argument n (shape) , which can be a tuple representing the dimensions of the array, or a single integer for a one-dimensional array and returns an array having all values zero’s.
You can use
zeros()function to create a
4x4matrix and using
slicingto set its border values to 1. For example:
2. Using "pad()" function:The "pad()" function in NumPy is used to add values to the edges of an array.
numpy.pad(array, pad_width, mode='constant', **kwargs)
You create zeros array and then pad all border elements with 1. For example:
3. Using "meshgrid(): function:It is used to create a coordinate grid from two or more one-dimensional arrays representing the coordinates of a set of points in a multi-dimensional space.
X, Y = np.meshgrid(x, y, indexing='xy')
meshgrid()function returns two multi-dimensional arrays
Ythat represent the coordinates of each point in the grid. The shape of
Ywill be the same, and it will be equal to the product of the lengths of the input arrays.
meshgrid(), we can create our required array shown below:
4. By "indices()" and "where()" function:
indices()method is used to create an array of indices that can be used to index into another array. The method returns an array with the same shape as the input array, where each element of the output array contains a tuple of indices that can be used to index into the input array.
where()function is a powerful tool for array manipulation in Python. It returns the indices of elements in an input array where a specified condition is true.
Following example, you can create
5x5 array having all values 1 and then we find indices and replace all elements except border elements with 0.