Having trouble working through more complex array slicing

40 views Asked by At

I'm working through the 100 numpy exercise list. One of the questions asks for you to devise an array of all ones, and then add a border of 0's.

There are two ways given to solve this. The first makes a lot sense (just using the .pad method, etc.) The second relies on more complex slicing. The code given for this is as follows:

import numpy as np

Z = np.ones((5, 5)) 
Z[:, [0, -1]] = 0
Z[[0, -1], :] = 0
print(Z)

Can anyone clear up for me what is going on in this code? I tried playing around with it, but some of the ways it changes don't make a lot of intuitive sense. For instance, if I just delete line 2, seemingly nothing changes? But if I change the second value in line 3 from -1 to 3, a lot changes.

As a minor addendum, could anyone explain to me why methods like np.ones etc. require two sets of parentheses?

1

There are 1 answers

1
Matt Hall On
  • Line 1: make an array of 1's with shape (5, 5) (hence the two sets of parentheses: one to call the function, one to provide the shape tuple).
  • Line 2: set the first and last (index -1) column to 0. Unpacking the slice: the : means 'everything in the first dimension' (i.e. all rows) and the [0, -1] means 'the first and last' (you're allowed to index with a list or array in NumPy, not just with integers).
  • Line 3: set the first and last row to 0.
  • Line 4: print it.

If you delete line 2, something changes, look again.