How to get the number of dimensions of a matrix using NumPy in Python?
Syntax: no_of_dimensions = numpy.ndarray.ndim
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- Create an n-dimensional matrix using numpy package.
- Use ndim attribute available with numpy array as numpy_array_name.ndim to get the number of dimensions.
- Alternatively, we can use shape attribute to get the size of each dimension and then use len() function for the number of dimensions.
- Use numpy.array() function to convert a list to numpy array and use one of the above two ways to get the number of dimensions.
Type of value obtained: <class 'int'> Dimensions in _1darr are: 1 Dimensions in _2darr are: 2 Dimensions in _3darr are: 3 Dimensions in _3darr are: 3 Dimensions in __1darr are: 1 Dimensions in __2darr are: 2