Python NumPy: How to Check if an Array is 1D or Multidimensional
Understanding the dimensionality of your NumPy arrays is fundamental for many array operations, manipulations, and when interfacing with other libraries that expect specific array shapes. A 1D array (vector) behaves differently from a 2D array (matrix) or higher-dimensional arrays (tensors) in terms of indexing, iteration, and mathematical operations. NumPy provides a simple and direct way to ascertain an array's dimensionality.
This guide will clearly explain how to use the ndarray.ndim
attribute to check if a NumPy array is one-dimensional (1D) or multidimensional (2D, 3D, etc.). We'll also cover how to handle arrays that might have "empty" or "squeezable" dimensions using numpy.squeeze()
before checking ndim
.
Understanding Array Dimensions in NumPy
In NumPy, the "dimension" of an array refers to the number of axes or indices required to access a specific element.
- 0D Array (Scalar): A single number (e.g.,
np.array(5)
). It hasndim = 0
. - 1D Array (Vector): A sequence of numbers, like a list (e.g.,
np.array([1, 2, 3])
). It hasndim = 1
. - 2D Array (Matrix): A table of numbers, like a list of lists where inner lists have the same length (e.g.,
np.array([[1, 2], [3, 4]])
). It hasndim = 2
. - 3D Array (Tensor): A collection of matrices (e.g.,
np.array([[[1],[2]], [[3],[4]]])
). It hasndim = 3
, and so on.
An array is considered "multidimensional" if its ndim
is greater than 1.
Using the ndarray.ndim
Attribute to Check Dimensions
Every NumPy ndarray
object has an attribute called ndim
which directly stores the number of its dimensions as an integer.
import numpy as np
# Example 1D array
array_1d = np.array([10, 20, 30, 40, 50])
print(f"array_1d: {array_1d}")
print(f"Number of dimensions for array_1d (array_1d.ndim): {array_1d.ndim}")
print()
# Example 2D array
array_2d = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(f"array_2d:\n{array_2d}")
print(f"Number of dimensions for array_2d (array_2d.ndim): {array_2d.ndim}")
print()
# Example 3D array
array_3d = np.array([
[[1], [2]],
[[3], [4]],
[[5], [6]]
]) # Shape (3, 2, 1)
print(f"array_3d (shape {array_3d.shape}):\n{array_3d}")
print(f"Number of dimensions for array_3d (array_3d.ndim): {array_3d.ndim}")
print()
Output:
array_1d: [10 20 30 40 50]
Number of dimensions for array_1d (array_1d.ndim): 1
array_2d:
[[1 2 3]
[4 5 6]]
Number of dimensions for array_2d (array_2d.ndim): 2
array_3d (shape (3, 2, 1)):
[[[1]
[2]]
[[3]
[4]]
[[5]
[6]]]
Number of dimensions for array_3d (array_3d.ndim): 3
Checking if an Array is One-Dimensional (ndim == 1
)
You can check if an array is 1D by comparing its ndim
attribute to 1.
import numpy as np
array_1d_test = np.array([5, 10, 15])
array_2d_test = np.array([[5], [10], [15]]) # This is a 2D column vector
if array_1d_test.ndim == 1:
print(f"array_1d_test (shape {array_1d_test.shape}) is one-dimensional.")
else:
print(f"array_1d_test (shape {array_1d_test.shape}) is multidimensional (ndim={array_1d_test.ndim}).")
if array_2d_test.ndim == 1:
print(f"array_2d_test (shape {array_2d_test.shape}) is one-dimensional.")
else:
print(f"array_2d_test (shape {array_2d_test.shape}) is multidimensional (ndim={array_2d_test.ndim}).")
Output:
array_1d_test (shape (3,)) is one-dimensional.
array_2d_test (shape (3, 1)) is multidimensional (ndim=2).
Checking if an Array is Multidimensional (ndim > 1
)
An array is multidimensional if its ndim
is greater than 1.
import numpy as np
# array_1d and array_2d from above
array_1d = np.array([5, 10, 15])
array_2d = np.array([[5], [10], [15]]) # This is a 2D column vector
if array_1d.ndim > 1:
print(f"array_1d (ndim={array_1d.ndim}) is multidimensional.")
else:
print(f"array_1d (ndim={array_1d.ndim}) is one-dimensional (or scalar if ndim=0).")
if array_2d.ndim > 1:
print(f"array_2d (ndim={array_2d.ndim}) is multidimensional.")
else:
print(f"array_2d (ndim={array_2d.ndim}) is one-dimensional (or scalar if ndim=0).")
Output:
array_1d (ndim=1) is one-dimensional (or scalar if ndim=0).
array_2d (ndim=2) is multidimensional.
Checking for Specific Dimensionality (e.g., ndim == 2
for 2D)
You can check for any specific number of dimensions.
import numpy as np
# array_2d and array_3d from above
array_2d = np.array([
[1, 2, 3],
[4, 5, 6]
])
array_3d = np.array([
[[1], [2]],
[[3], [4]],
[[5], [6]]
]) # Shape (3, 2, 1)
if array_2d.ndim == 2:
print(f"array_2d (ndim={array_2d.ndim}) is two-dimensional.")
else:
print(f"array_2d (ndim={array_2d.ndim}) is NOT two-dimensional.")
if array_3d.ndim == 2:
print(f"array_3d (ndim={array_3d.ndim}) is two-dimensional.")
else:
print(f"array_3d (ndim={array_3d.ndim}) is NOT two-dimensional.")
Output:
array_2d (ndim=2) is two-dimensional.
array_3d (ndim=3) is NOT two-dimensional.
Handling "Empty" or Squeezable Dimensions with numpy.squeeze()
Sometimes, an array might have dimensions of size 1 that you might want to ignore or "squeeze out" when determining its essential dimensionality. For example, np.array([[1, 2, 3]])
has shape=(1, 3)
and ndim=2
, but it effectively represents a single row of data.
The Effect of Squeezable Dimensions on ndim
import numpy as np
# Array with a leading dimension of size 1
array_squeezable_rows = np.array([[10, 20, 30]]) # Shape: (1, 3)
print(f"array_squeezable_rows:\n{array_squeezable_rows}")
print(f"Shape: {array_squeezable_rows.shape}, ndim: {array_squeezable_rows.ndim}")
print()
# Array with a trailing dimension of size 1
array_squeezable_cols = np.array([[10], [20], [30]]) # Shape: (3, 1)
print(f"array_squeezable_cols:\n{array_squeezable_cols}")
print(f"Shape: {array_squeezable_cols.shape}, ndim: {array_squeezable_cols.ndim}")
Output:
array_squeezable_rows:
[[10 20 30]]
Shape: (1, 3), ndim: 2
array_squeezable_cols:
[[10]
[20]
[30]]
Shape: (3, 1), ndim: 2
Both of these are technically 2D, even though they might conceptually represent 1D data.
Using np.squeeze()
Before Checking ndim
The numpy.squeeze(a, axis=None)
function removes axes of length one from an array. Applying this before checking ndim
can give you the dimensionality of the "core" data.
import numpy as np
# array_squeezable_rows (shape (1,3), ndim 2)
array_squeezable_rows = np.array([[10, 20, 30]])
# array_squeezable_cols (shape (3,1), ndim 2)
array_squeezable_cols = np.array([[10], [20], [30]])
squeezed_rows = np.squeeze(array_squeezable_rows)
print(f"Squeezed array_squeezable_rows:\n{squeezed_rows}")
print(f"Shape: {squeezed_rows.shape}, ndim: {squeezed_rows.ndim}")
print()
squeezed_cols = np.squeeze(array_squeezable_cols)
print(f"Squeezed array_squeezable_cols:\n{squeezed_cols}")
print(f"Shape: {squeezed_cols.shape}, ndim: {squeezed_cols.ndim}")
print()
# Example checking ndim after squeeze
if squeezed_rows.ndim == 1:
print("After squeezing, array_squeezable_rows is effectively 1D.")
Output:
Squeezed array_squeezable_rows:
[10 20 30]
Shape: (3,), ndim: 1
Squeezed array_squeezable_cols:
[10 20 30]
Shape: (3,), ndim: 1
After squeezing, array_squeezable_rows is effectively 1D.
Using np.squeeze()
is useful when an array might have acquired singleton dimensions through operations like np.newaxis
or certain slicing patterns, and you want to assess the dimensionality of the underlying meaningful data.
Conclusion
Determining whether a NumPy array is 1D or multidimensional is straightforward using the ndarray.ndim
attribute:
- If
array.ndim == 1
, the array is one-dimensional (a vector). - If
array.ndim > 1
, the array is multidimensional (e.g., a 2D matrix, 3D tensor, etc.). - If
array.ndim == 0
, the array is a scalar.
For cases where an array might have dimensions of size one that don't contribute to its essential dimensionality for your purpose, preprocessing with numpy.squeeze()
before checking ndim
can provide a more practical measure of its "effective" dimensions. This simple attribute is fundamental for writing robust NumPy code that handles arrays of various shapes correctly.