Sparker0i
Sparker0i

Reputation: 1861

Numpy array change value of inner elements

I create an array in numpy as

a = np.ones([5 , 5])

I will then get an output as 5x5 array full of 1s. I would like to keep the outer elements as 1, and inner elements as 0. So I would like output to be:

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

Is there any way with which we could do this in a single line? (I have read about inner() but I dont know how to get it working with this single array)

Upvotes: 2

Views: 606

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

Yes, we can use slicing for this:

a[1:-1, 1:-1] = 0

Or for a generic multidimensional array:

a[(slice(1, -1),) * a.ndim] = 0

but usually it would be better to construct such matrix in another way. This produces:

>>> a = np.ones([5 , 5])
>>> a[1:-1, 1:-1] = 0
>>> a
array([[1., 1., 1., 1., 1.],
       [1., 0., 0., 0., 1.],
       [1., 0., 0., 0., 1.],
       [1., 0., 0., 0., 1.],
       [1., 1., 1., 1., 1.]])

and for instance for a 3d case (imagine some sort of cube):

>>> a = np.ones([5 , 5, 5])
>>> a[(slice(1, -1),) * a.ndim] = 0
>>> a
array([[[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., 0., 0., 0., 1.],
        [1., 0., 0., 0., 1.],
        [1., 0., 0., 0., 1.],
        [1., 1., 1., 1., 1.]],

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

       [[1., 1., 1., 1., 1.],
        [1., 0., 0., 0., 1.],
        [1., 0., 0., 0., 1.],
        [1., 0., 0., 0., 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.]]])

Upvotes: 2

Related Questions