28 Mar Dimensions in Numpy Arrays
Dimensions of an array in NumPy are also called the Rank of an Array. Here, we will see how to check how many dimensions an array has used with the numpy.ndarray.ndim. With that, we will also see some examples of creating 0D, 1D, 2D, and 3D arrays:
- Create a 0-Dimensional NumPy array and check the dimensions
- Create a 1-Dimensional NumPy array and check the dimensions
- Create a 2-Dimensional NumPy array and check the dimensions
- Create a 3-Dimensional NumPy array and check the dimensions
Create a Zero-dimensional NumPy array
Let us create a zero-dimensional numpy array and check the dimensions using the ndim attribute:
1 2 3 4 5 6 7 8 |
import numpy as np n = np.array(25) print(type(n)) print(n.shape) print("Dimensions = ",n.ndim) |
Output
1 2 3 4 5 |
<class 'numpy.ndarray'> () Dimensions = 0 |
Create a One-dimensional NumPy array
Let us create a one-dimensional numpy array and check the dimensions using the ndim attribute:
1 2 3 4 5 6 7 8 |
import numpy as np n = np.array([10, 20, 30]) print(type(n)) print(n.shape) print("Dimensions = ",n.ndim) |
Output
1 2 3 4 5 |
<class 'numpy.ndarray'> (3,) Dimensions = 1 |
Create a Two-dimensional NumPy array
Let us create a two-dimensional numpy array and check the dimensions using the ndim attribute. A 2D NumPy array is like a matrix. Let us see an example to create a 2D NumPy array:
1 2 3 4 5 6 7 8 |
import numpy as np n = np.array([[1,3,5],[4,8,12]]) print(type(n)) print(n.shape) print("Dimensions = ",n.ndim) |
Output
1 2 3 4 5 |
<class 'numpy.ndarray'> (2, 3) Dimensions = 2 |
Video Tutorial
Create a Three-dimensional NumPy array
Let us create a three-dimensional numpy array and check the dimensions using the ndim attribute. A 3D array has 2D arrays as elements i.e. matrix as elements. Let us see an example to create a 3D NumPy array:
1 2 3 4 5 6 7 8 |
import numpy as np n = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]) print(type(n)) print(n.shape) print("Dimensions = ",n.ndim) |
Output
1 2 3 4 5 |
<class 'numpy.ndarray'> (2, 2, 3) Dimensions = 3 |
Video Tutorial
Check how many dimensions an array has
Let us see our last example to check the dimensions of two arrays:
1 2 3 4 5 6 7 8 9 10 11 12 |
import numpy as np n1 = np.array(10) n2 = np.array([10, 20, 30]) print(n1.ndim) print(n1.shape) print(n2.ndim) print(n2.shape) |
Output
1 2 3 4 5 6 |
0 () 1 (3,) |
Video Tutorial
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments