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?
(5, 5)
(hence the two sets of parentheses: one to call the function, one to provide the shape tuple).:
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).If you delete line 2, something changes, look again.