The ndarray
class 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, 3 rows and 4 columns (alternatively we 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. We 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
In: b[:,0,0] Out: array([ 0, 12])
Select the first floor in this code:
In: b[0] Out: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
We can also write this:
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 this:
In: b[0, ...] Out: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
Furthermore, get the second row on the first floor:
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, 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 this:
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])
Select every second element of that slice as follows:
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 as follows:
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]]])