Oy mates,
I am learning numpy on my own and getting a pretty good handle on it, a few concepts elude me even after reading the documentation though. I am trying to go through this matrix and make every second row have 10s all the way through it.
data = np.ones(50).reshape(5,10) xmax = data.shape[0] ymax = data.shape[1] data[range(xmax)::2,range(ymax)] = 10
The last line of code is incorrect. I know how to use slicing by using semi colons – list[start:stop:step]
and I know how to use fancy indexing to go through matrices by using commas ndarray[range(end1),range(end2)]
but how do I combine these two methods?
How do I step through a multidimensional array, using range, while simultaneously having a set start, stop, and step?
Advertisement
Answer
I think what you want is this:
>>> data[range(xmax)[::2],:] = 10 >>> data array([[ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.], [ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [ 10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]])'
The issue is here:
>>> range(xmax):: File "<stdin>", line 1 range(xmax):: ^ SyntaxError: invalid syntax
You need to apply the slice syntax to the range explicitly:
>>> range(xmax)[::2] [0, 2, 4]
For general reference you can do:
data[np.arange(start1, end1, step1), np.arange(start2, end2, step2)]
Where the first np.arange
chooses the rows and the second np.aranage
chooses the columns.
A few references that may help: