Axis and Dimension in NumPy
Axis and dimensions are fundamental concepts in NumPy for understanding and manipulating the multi-dimensional arrays.
This article describes the basics of array, dimension, and axis, and how to use them for manipulation multi-dimensional arrays.
Array
It is essential to understand array before learning about axes and dimensions.
An array is a homogeneous container of numerical elements (int, float, or a combination of them).
Example of a simple NumPy 1-dimensional (D) array:
# import package
import numpy as np
# 1-D array
x = np.array([1, 2, 3])
x
# output
array([1, 2, 3])
Dimension
These arrays can have multiple dimensions (number of levels of depth in an array) such as 0-D, 1-D, 2-D, 3-D, and so on.
For example, the 2-D array will have two levels (rows and columns), and the 3-D array will have three levels (rows, columns, depth).
The example of 0-D, 1-D, and 2-D arrays:
# import package
import numpy as np
# 0-D array (scalars)
x = np.array(2)
# 1-D array (vectors)
x = np.array([1, 2, 3])
# 2-D array (matrix)
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
The ndim
function can be used for determining the number of dimensions of an array.
Let’s take an example of 2-D array:
# 2-D array (matrix)
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr_2d.ndim
# output
2
The given array is 2-D.
Now, check with 3-D array example:
# 3-D array
arr_3d = np.array([[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]])
arr_3d.ndim
# output
3
The given array is 3-D.
Axis
In NumPy, axes provide the directions for navigating and manipulating the array elements within a multi-dimensional array.
Axes start with 0 and grow in number as the dimensions of the array increase.
When axis=0, it refers to the first level (function applied on each column) in a 2-D array. Similarly, when axis=1, it refers to the second level (function applied on each row) in a 2-D array
The following example explains how to use axes in NumPy arrays for data manipulation.
Get the sum of rows elements in a 2-D array,
# 2-D array (matrix)
arr_2d = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
arr_2d
# output
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# get sum along rows (axis=0)
arr_2d.sum(axis=0)
# output
array([12, 15, 18])
# get sum along columns (axis=1)
arr_2d.sum(axis=1)
# output
array([6, 15, 24])
In the above 2-D array, the axis=0 elements are [1, 4, 7]
, [2, 5, 8]
, and [3, 6, 9]
. The sum of these elements are [12, 15, 18]
.
Similarly, the axis=1 elements are [1, 2, 3]
, [4, 5, 6]
, and [7, 8, 9]
. The sum of these elements are [6, 15, 24]
.