how is axis indexed in numpy's array?

From Numpy's tutorial, axis can be indexed with integers, like 0 is for column, 1 is for row, but I don't grasp why they are indexed this way? And How do I figure out each axis' index when coping with multidimensional array?


By definition, the axis number of the dimension is the index of that dimension within the array's shape. It is also the position used to access that dimension during indexing.

For example, if a 2D array a has shape (5,6), then you can access a[0,0] up to a[4,5]. Axis 0 is thus the first dimension (the "rows"), and axis 1 is the second dimension (the "columns"). In higher dimensions, where "row" and "column" stop really making sense, try to think of the axes in terms of the shapes and indices involved.

If you do .sum(axis=n), for example, then dimension n is collapsed and deleted, with each value in the new matrix equal to the sum of the corresponding collapsed values. For example, if b has shape (5,6,7,8), and you do c = b.sum(axis=2), then axis 2 (dimension with size 7) is collapsed, and the result has shape (5,6,8). Furthermore, c[x,y,z] is equal to the sum of all elements b[x,y,:,z].


If at all anyone need this visual description of a shape=(3,5) array:

Numpy array axis 0 and 1


You can grasp axis in this way:

>>> a = np.array([[[1,2,3],[2,2,3]],[[2,4,5],[1,3,6]],[[1,2,4],[2,3,4]],[[1,2,4],[1,2,6]]])
array([[[1, 2, 3],
    [2, 2, 3]],

   [[2, 4, 5],
    [1, 3, 6]],

   [[1, 2, 4],
    [2, 3, 4]],

   [[1, 2, 4],
    [1, 2, 6]]])
>>> a.shape
(4,2,3)

I created an array of a shape with different values(4,2,3) so that you can tell the structure clearly. Different axis means different 'layer'.

That is, axis = 0 index the first dimension of shape (4,2,3). It refers to the arrays in the first []. There are 4 elements in it, so its shape is 4:

  array[[1, 2, 3],
        [2, 2, 3]],

  array[[2, 4, 5],
        [1, 3, 6]],

  array[[1, 2, 4],
        [2, 3, 4]],

  array[[1, 2, 4],
        [1, 2, 6]]

axis = 1 index the second dimension in shape(4,2,3). There are 2 elements in each array of the layer: axis = 0,e.c. In the array of

 array[[1, 2, 3],
       [2, 2, 3]]

. The two elements are:

array[1, 2, 3]

array[2, 2, 3]

And the third shape value means there are 3 elements in each array element of layer: axis = 2. e.c. There are 3 elements in array[1, 2, 3]. That is explicit.

And also, you can tell the axis/dimensions from the number of [] at the beginning or in the end. In this case, the number is 3([[[), so you can choose axis from axis = 0, axis = 1 and axis = 2.