Axes basically tell you the direction along rows and columns. The number of axes is called dimension of Numpy array.
The numbering of the axis starts from 0. For 1-D Numpy array, there is only one axis which is axis0. For 2-D Numpy array, there are two axes which are- axis0 and axis1. For 3-D Numpy array, there are three axes which are- axis0, axis1, and axis2.
In 1-Dimensional array, axis0 goes horizontally across the columns.
In 2-Dimensional array, axis0 goes vertically across the rows and axis1 goes horizontally across the columns.
You know that 3-Dimensional array is simply a collection of 2-Dimensional array. axis0 goes from one element of 2-Dimensional array to another element present just opposite to another 2-Dimensional array and so on, axis1 goes vertically across the rows and axis2 goes horizontally across the columns.
Axis is generally used in aggregate functions like
mean(), etc. where we specify the axis along which we have to perform aggregation.
Let's see an example of how we can use
sum() function to perform addition-
import numpy as np a = np.array([1, 2, 3, 4, 5]) print('Numpy array a: \n', a) print('Sum of all the elements: ', np.sum(a, axis=0)) b = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) print('Numpy array b: \n', b) print('Sum of elements along axis 0: ', np.sum(b, axis=0)) print('Sum of elements along axis 1: ', np.sum(b, axis=1))
Output of the above program
Numpy array a: [1 2 3 4 5] Sum of all the elements: 15 Numpy array b: [[1 2 3 4] [5 6 7 8]] Sum of elements along axis 0: [ 6 8 10 12] Sum of elements along axis 1: [10 26]