Next / Previous / Contents / Shipman's homepage

5.4. Three or more dimensions

The figure below shows the numbering of indices of a 3-d array. The column index is always last. The row index precedes the column index for arrays of two or more dimensions. For a 3-d array, the “plane” index is the first index.

Here is a conversational example of the creation of an array shaped like the above illustration.

>>> import numpy as np
>>> d3 = np.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]]])
>>> print d3
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

To extract one element from a three-dimensional array, use an expression of this form:

A[plane, row, col]

For example:

>>> d3[0,0,0]
0
>>> d3[0,0,1]
1
>>> d3[0,1,0]
4
>>> d3[1,0,0]
12
>>> d3[1,2,3]
23

Slicing generalizes to any number of dimensions. For example:

>>> print d3
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
>>> d3[:,:,1:3]
array([[[ 1,  2],
        [ 5,  6],
        [ 9, 10]],

       [[13, 14],
        [17, 18],
        [21, 22]]])