Last updated: Apr 12, 2024
Reading timeยท3 min
Use the ndim
attribute on the NumPy array to check if it is multidimensional
or one-dimensional.
The ndim
attribute returns the number of array dimensions:
import numpy as np arr1 = np.array([2, 4, 6, 8]) print(arr1.ndim) # ๐๏ธ 1 print('-' * 50) if arr1.ndim == 1: # ๐๏ธ this runs print('The array is one-dimensional') else: print('The array is multidimensional') print('-' * 50) arr2 = np.array([[1, 2, 3], [4, 5, 6]]) print(arr2.ndim) # ๐๏ธ 2
The ndarray.ndim attribute returns the number of array dimensions.
import numpy as np arr1 = np.array([2, 4, 6, 8]) print(arr1.ndim) # ๐๏ธ 1 arr2 = np.array([[1, 2, 3], [4, 5, 6]]) print(arr2.ndim) # ๐๏ธ 2
If you need to check if the array is one-dimensional, check if the ndim
attribute returns 1
.
import numpy as np arr1 = np.array([2, 4, 6, 8]) print(arr1.ndim) # ๐๏ธ 1 print('-' * 50) if arr1.ndim == 1: # ๐๏ธ this runs print('The array is one-dimensional') else: print('The array is multidimensional')
If the attribute returns 1
, then the array is one-dimensional.
Otherwise, it is at least two-dimensional.
If you need to check if the array is multidimensional, check if the ndim
attribute returns a value greater than 1
.
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr.ndim) # ๐๏ธ 2 if arr.ndim > 1: # ๐๏ธ this runs print('The array is multidimensional') else: print('The array is one-dimensional')
You can use the same approach to check if the NumPy array is two-dimensional.
import numpy as np arr = np.array([[1, 2, 3], [4, 5, 6]]) print(arr.ndim) # ๐๏ธ 2 if arr.ndim == 2: # ๐๏ธ this runs print('The array is two-dimensional') else: print('The array is NOT two-dimensional')
numpy.squeeze()
If your array might have empty dimensions, use the
numpy.squeeze()
method before accessing the ndim
attribute.
import numpy as np arr = np.array([[1, 2, 3]]) print(arr.ndim) # ๐๏ธ 2 arr = np.squeeze(arr) print(arr.ndim) # ๐๏ธ 1
The array in the example has an empty dimension.
import numpy as np arr = np.array([[1, 2, 3]]) print(arr) # ๐๏ธ [[1 2 3]] print(arr.ndim) # ๐๏ธ 2
The numpy.squeeze
method removes the axes of length one from the supplied
array.
import numpy as np arr = np.array([[1, 2, 3]]) print(arr) # ๐๏ธ [[1 2 3]] print(arr.squeeze()) # ๐๏ธ [1 2 3]
Accessing the ndim
attribute after calling squeeze()
produces a different
result.
import numpy as np arr = np.array([[1, 2, 3]]) print(arr.ndim) # ๐๏ธ 2 arr = np.squeeze(arr) print(arr.ndim) # ๐๏ธ 1
You can learn more about the related topics by checking out the following tutorials: