NumPy ndarray.ndim Attribute



The NumPy ndarray.ndim attribute is used to get the number of dimensions (axes) of a NumPy array.

Understanding the dimensions of an array is important when performing operations in data analysis and scientific computing, as it affects how data is accessed and manipulated.

The ndim attribute is simple to use and provides a quick way to check the shape complexity of your array.

Usage of the ndim Attribute in NumPy

The ndim attribute can be accessed directly from a NumPy array object to determine its number of dimensions.

It is commonly used to understand the structure of an array before performing operations like reshaping, slicing, or broadcasting.

Below are some examples that demonstrate how ndim can be applied to various arrays in NumPy.

Example: Basic Usage of ndim Attribute

In the following example, we create a simple 1-dimensional array and use the ndim attribute to find out the number of dimensions it has −

import numpy as np

# Creating a 1-dimensional array
arr = np.array([1, 2, 3, 4])
print(arr.ndim)

Following is the output obtained −

1

Example: Checking Dimensions of a 2D Array

In this example, we create a 2-dimensional array and use the ndim attribute to determine its number of dimensions −

import numpy as np

# Creating a 2-dimensional array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.ndim)

This will produce the following result −

2

Example: Higher Dimensional Arrays

In this example, we create a 3-dimensional array and use the ndim attribute to find out the number of dimensions −

import numpy as np

# Creating a 3-dimensional array
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr.ndim)

Following is the output of the above code:

3

Example: ndim with Empty Arrays

In the following example, we check the number of dimensions of an empty array. This demonstrates that even an empty array has a dimensionality −

import numpy as np

# Creating an empty array
arr = np.array([])
print(arr.ndim)

The output obtained is as shown below −

1
numpy_array_attributes.htm
Advertisements