How to add border around NumPy array?

The task is to create a special array that contains 1 on the border and 0 inside the border that looks like the below:

[[1. 1. 1. 1. 1.],
 [1. 0. 0. 0. 1.],
 [1. 0. 0. 0. 1.],
 [1. 1. 1. 1. 1.]]

I have coded this array but not getting desired output. Can you highlight my mistake or provide an alternative if you have one?
Here’s my code below:

import numpy as np
array = np.zeros((4, 4))
array[0,:1] = 1
array[-1,:0] = 1
array[1:,0] = 1
array[0:,-1] = 1
print(array)

Output:
[[1. 0. 0. 1.]
 [1. 0. 0. 1.]
 [1. 0. 0. 1.]
 [1. 0. 0. 1.]]

Hey you can use theindices() method. It 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. The 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.

Let’s understand it by an example, you can create 5x5 array having all values 1 and then we find indices and replace all elements except border elements with 0.

Yes, there is a mistake in your attached code and the problem is in the slicing lines you used to fill the ones at the border of the array. Here is the correct code:

  • array[0, :] = 1 sets 1 in the first row in the array.
  • array[-1, :] = 1 sets 1 in the last row in the array.
  • array[:, 0] = 1 sets 1 in the first column in the array.
  • array[:, -1] = 1 sets 1 in the last column in the array.
  • These lines of code will set 1 in the borders of the array and gives you your desired output.