NumPy is an open-source library for Python that enables easy computing in Python. It was developed by multiple contributors in 2005 and is an abbreviation of Numerical Python.
You can find details on installing NumPy and creating an array here- The NumPy Library in Python.
This post is about NumPy array dimensions and accessing them.
Dimensions of NumPy Arrays
NumPy arrays can be 0-D (0 Dimensional), 1-D, 2-D, 3-D and so on.
0-D arrays have only 1 value. In other words, all the elements of an array are 0-D arrays.
1-D arrays are arrays that have 0-D arrays as their elements. Or, in other words, a ‘normal’, basic array is a 1-D array
2-D arrays have 1-D arrays as their elements. 2-D arrays basically have 1 or more arrays inside them. So, now you have an array with multiple arrays in it.
This keeps going on till an x number of dimensions.
For example-
import numpy as np
"""A 0-D array"""
arr_0d=np.array(32)
"""A 1-D array"""
arr_1d=np.array([2, 4, 8, 16, 32])
"""A 2-D array"""
arr_2d=np.array([[2, 4, 8], [16, 32, 64]])
print(arr_0d)
print(arr_1d)
print(arr_2d)
The output-
[ 2 4 8 16 32]
[[ 2 4 8]
[16 32 64]]
Checking the number of dimensions of an array
You can check the number of dimensions of an array using the
ndim
attribute. This attribute returns an integer value of the
number of dimensions.
For example-
import numpy as np
arr1=np.array(2)
arr2=np.array([2, 4, 8])
arr3=np.array([[2, 4, 8], [16, 32, 64]])
print(arr1.ndim)
print(arr2.ndim)
print(arr3.ndim)
The output-
0
1
2
Accessing Array Items
You can access array items the same way as lists by
name_of_array[index]
. This is only for 1-D arrays.
For example-
import numpy as np
arr=([2, 4, 8, 16])
"""Prints the third element as indexing begins from 0"""
print(arr[2])
The output-
8
You can access 2-D arrays by specifying the dimension index first, and then the element index, separated by a comma. This should become clear with the following example-
import numpy as np
arr=np.array([[1, 2, 3], [4, 5, 6]])
print(arr[1,1])
The output-
5
Here, the dimension index is
1
, so the dimension will be [4, 5, 6]
. Now, the
element dimension is also 1
, so the element printed is
5
, which is the second element of [4, 5, 6]
.
Similarly, for 3-D arrays, the outermost dimension index is given first, along with the indices of the inner dimensions.
For example-
import numpy as np
arr=np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[1, 0, 2])
The output-
9
That is all for this post. Hope it was informative!
Follow this blog for more such content on Python and coding.
Happy coding,
Aarav Iyer