0
0
NumpyHow-ToBeginner ยท 3 min read

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 ndim as a function like array.ndim() instead of accessing it as an attribute array.ndim.
  • Confusing ndim with shape, 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

PropertyDescriptionExample
ndimNumber of dimensions of the arrayarray.ndim
shapeSize of each dimensionarray.shape
sizeTotal number of elementsarray.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.