# How to Use the Numpy ndim() Function in Python

09/28/2021

Contents

In this article, you will learn how to use the Numpy ndim() function in Python.

## Numpy ndim() Function

The NumPy ndim() function is used to get the number of dimensions of a NumPy array. It is a very useful function in data analysis and machine learning as it allows you to quickly check the shape of a NumPy array and ensure that it is compatible with other arrays or functions.

### Syntax

The ndim() function can be used on any NumPy array to return the number of dimensions. Here’s the syntax:

``numpy.ndim(arr)``

Where arr is the NumPy array for which we want to get the number of dimensions.

### Examples

For example, let’s create a NumPy array with shape (3, 4, 5):

``````import numpy as np

arr = np.zeros((3, 4, 5))
print(arr.ndim) # Output: 3
``````

In this example, we create a NumPy array using the np.zeros() function with the shape of (3, 4, 5). Then, we call the ndim() function on this array to get the number of dimensions, which is 3.

The ndim() function returns an integer that represents the number of dimensions of the NumPy array. It will always return a value greater than or equal to 1, as even a 1D array has one dimension.

Here’s an example of using the ndim() function to check if a given array is 1D or not:

``````import numpy as np

arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([[1, 2], [3, 4]])

print(arr1.ndim) # Output: 1
print(arr2.ndim) # Output: 2
``````

In this example, we create two NumPy arrays, one with shape (4,) and another with shape (2, 2). Then, we call the ndim() function on each of them to get the number of dimensions. As we can see, the first array has 1 dimension and the second array has 2 dimensions.