A ndarray
supports slicing over multiple dimensions. For convenience, we refer to many dimensions at once, with an ellipsis.
arange
function and reshape it:In: b = arange(24).reshape(2,3,4) In: b.shape Out: (2, 3, 4) In: b Out: array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]])
The array b
has 24
elements with values 0
to 23
and we reshaped it to be a two-by-three-by-four, three-dimensional array. We can visualize this as a two-story building with 12 rooms on each floor, three rows and four columns (alternatively, you can think of it as a spreadsheet with sheets, rows, and columns). As you have probably guessed, the reshape
function changes the shape of an array. You give it a tuple of integers, corresponding to the new shape. If the dimensions are not compatible with the data, an exception is thrown.
In: b[0,0,0] Out: 0
:
(colon) because we just need to specify the floor number and omit the other indices:In: b[:,0,0] Out: array([ 0, 12]) This selects the first floor In: b[0] Out: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
We could also have written:
In: b[0, :, :] Out: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
An …
(ellipsis) replaces multiple colons, so, the preceding code is equivalent to:
In: b[0, ...] Out: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
Further, we get the second row on the first floor with:
In: b[0,1] Out: array([4, 5, 6, 7])
In: b[0,1,::2] Out: array([4, 6])
In: b[...,1] Out: array([[ 1, 5, 9], [13, 17, 21]])
Similarly, we can select all the rooms on the second row, regardless of floor and column, by writing the following code snippet:
In: b[:,1] Out: array([[ 4, 5, 6, 7], [16, 17, 18, 19]])
If we want to select rooms on the ground floor second column, then type the following code snippet:
In: b[0,:,1] Out: array([1, 5, 9])
In: b[0,:,-1] Out: array([ 3, 7, 11])
If we want to select rooms on the ground floor, last column reversed, then type the following code snippet:
In: b[0,::-1, -1] Out: array([11, 7, 3])
Every second element of that slice:
In: b[0,::2,-1] Out: array([ 3, 11])
The command that reverses a one-dimensional array puts the top floor following the ground floor:
In: b[::-1] Out: array([[[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]], [[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]])