NumPy ndarray.ndim

The ndarray.ndim attribute in NumPy returns the number of dimensions (axes) of an array. It helps determine whether an array is 1D, 2D, 3D, or higher-dimensional.

Syntax

</>
Copy
ndarray.ndim

Attribute Details

AttributeTypeDescription
ndimintReturns the number of dimensions (axes) of the array.

Return Value

The ndim attribute returns an integer representing the number of dimensions in the array.


Examples

1. Checking Dimensions of Different Arrays

Let’s create and check the number of dimensions for different arrays.

</>
Copy
import numpy as np  

# Creating a 1D array  
arr_1d = np.array([1, 2, 3, 4, 5])  
print("1D array dimensions:", arr_1d.ndim)  

# Creating a 2D array  
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])  
print("2D array dimensions:", arr_2d.ndim)  

# Creating a 3D array  
arr_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])  
print("3D array dimensions:", arr_3d.ndim)

Output:

1D array dimensions: 1
2D array dimensions: 2
3D array dimensions: 3

The ndim attribute correctly identifies the number of dimensions in each array.

2. Checking Dimensions of Higher-Dimensional Arrays

Let’s create and check dimensions of a 4D and a 5D array.

</>
Copy
import numpy as np  

# Creating a 4D array  
arr_4d = np.random.rand(2, 2, 2, 2)  # Random 4D array with shape (2,2,2,2)
print("4D array dimensions:", arr_4d.ndim)  

# Creating a 5D array  
arr_5d = np.random.rand(2, 2, 2, 2, 2)  # Random 5D array with shape (2,2,2,2,2)
print("5D array dimensions:", arr_5d.ndim)

Output:

4D array dimensions: 4
5D array dimensions: 5

The ndim attribute correctly returns the number of dimensions for higher-dimensional arrays as well.

3. Checking Dimensions of an Empty Array

Even an empty array has a dimension value.

</>
Copy
import numpy as np  

# Creating an empty array  
empty_arr = np.array([])  
print("Empty array dimensions:", empty_arr.ndim)

Output:

Empty array dimensions: 1

An empty array in NumPy is considered a 1D array, even though it contains no elements.

4. Using ndim on a Scalar

A NumPy scalar has zero dimensions.

</>
Copy
import numpy as np  

# Creating a scalar (0D array)
scalar = np.array(42)  
print("Scalar dimensions:", scalar.ndim)

Output:

Scalar dimensions: 0

A scalar is considered a zero-dimensional array in NumPy.