How to Find ndim of Array in NumPy: Simple Guide
To find the number of dimensions of a NumPy array, use the
ndarray.ndim attribute. It returns an integer representing how many axes or dimensions the array has.Syntax
The syntax to find the number of dimensions of a NumPy array is simple:
array.ndim: Returns the number of dimensions (an integer).
Here, array is any NumPy array object.
python
import numpy as np array = np.array([[1, 2], [3, 4]]) number_of_dimensions = array.ndim print(number_of_dimensions)
Output
2
Example
This example shows how to create arrays with different dimensions and find their ndim values.
python
import numpy as np # 1D array array_1d = np.array([1, 2, 3]) print('1D array ndim:', array_1d.ndim) # 2D array array_2d = np.array([[1, 2, 3], [4, 5, 6]]) print('2D array ndim:', array_2d.ndim) # 3D array array_3d = np.array([[[1], [2]], [[3], [4]]]) print('3D array ndim:', array_3d.ndim)
Output
1D array ndim: 1
2D array ndim: 2
3D array ndim: 3
Common Pitfalls
Some common mistakes when checking the number of dimensions in NumPy arrays include:
- Trying to call
ndimas a function likearray.ndim()instead of accessing it as an attributearray.ndim. - Confusing
ndimwithshape, which returns the size of each dimension, not the count of dimensions.
python
import numpy as np array = np.array([1, 2, 3]) # Wrong: calling ndim as a function try: print(array.ndim()) except TypeError as e: print('Error:', e) # Right: access ndim as attribute print('Correct ndim:', array.ndim)
Output
Error: 'int' object is not callable
Correct ndim: 1
Quick Reference
| Property | Description | Example |
|---|---|---|
| ndim | Number of dimensions of the array | array.ndim |
| shape | Size of each dimension | array.shape |
| size | Total number of elements | array.size |
Key Takeaways
Use the attribute
array.ndim to get the number of dimensions of a NumPy array.ndim returns an integer representing how many axes the array has.Do not call
ndim as a function; it is an attribute, not a method.Remember that
shape gives the size of each dimension, not the count of dimensions.Arrays can have 1 or more dimensions, and
ndim helps identify this quickly.