Python Numpy - Get Array Shape or Dimensions
NumPy - Array Shape or Dimensions
To get the shape or dimensions of a NumPy Array, use ndarray.shape
, where ndarray
is the name of the NumPy array you are interested in. The ndarray.shape
property returns a tuple with the size of the array along each axis.
Examples
1. Get shape of multi-dimensional NumPy array
In the following example, we initialize a multi-dimensional numpy array. We will use the ndarray.shape
property to get the shape of the array programmatically.
Python Program
import numpy as np
#initialize an array
arr = np.array([[[11, 11, 9, 9],
[11, 0, 2, 0]],
[[10, 14, 9, 14],
[0, 1, 11, 11]]])
# get array shape
shape = arr.shape
print(shape)
Explanation:
- The array is a 3D array with two 2x4 matrices.
- The
arr.shape
returns a tuple of the form(2, 2, 4)
, representing the dimensions of the array: 2 matrices, 2 rows per matrix, and 4 columns per row.
Output
(2, 2, 4)
2. Get shape of 2D NumPy array
In the following example, we create a 2D numpy array with 2 rows and 4 columns. We will then use ndarray.shape
to get the shape.
Python Program
import numpy as np
#initialize an array
arr = np.array([[11, 11, 9, 9],
[11, 0, 2, 0]])
# get array shape
shape = arr.shape
print(shape)
Explanation:
- The array has 2 rows and 4 columns.
- The shape will be represented as a tuple
(2, 4)
.
Output
(2, 4)
3. Get shape of 1-Dimensional NumPy array
In this example, we take a one-dimensional numpy array with 4 elements and find its shape using ndarray.shape
.
Python Program
import numpy as np
#initialize an array
arr = np.array([11, 11, 9, 9])
# get array shape
shape = arr.shape
print(shape)
Explanation:
- The array has 4 elements, so its shape will be
(4,)
, indicating it's a 1D array with 4 elements.
Output
(4,)
4. Get shape of higher-dimensional NumPy array
In this example, we create a 4D numpy array. Let's see how the shape of such an array looks when analyzed.
Python Program
import numpy as np
#initialize a 4D array
arr = np.array([[[[11, 12, 13], [14, 15, 16]], [[17, 18, 19], [20, 21, 22]]],
[[[23, 24, 25], [26, 27, 28]], [[29, 30, 31], [32, 33, 34]]]])
# get array shape
shape = arr.shape
print(shape)
Explanation:
- This array is 4-dimensional with the shape
(2, 2, 2, 3)
: - 2 blocks (depth), each containing 2 matrices, each of size 2x3 (2 rows and 3 columns).
Output
(2, 2, 2, 3)
Summary
In this Numpy Tutorial, we learned how to get the shape of a given numpy array using the ndarray.shape
property. This method works for arrays of any dimension, whether 1D, 2D, or higher-dimensional arrays. We covered several examples to demonstrate the use of this function across different array types.