How to Get NumPy Array Shape?

To get the shape of a Python NumPy array use numpy.ndarray.shape property. The array shape can be defined as the number of elements in each dimension and dimension is defined as a number of indices or subscripts, that can specify an individual element of an array.

To get the size of the multi-dimensional array, use an attribute called shape which returns a tuple (x,y) where x is the number of rows and y is the number of columns in the array. In this article, I will explain how to get the shape of a NumPy array by using numpy.ndarray.shape property with examples.

1. Quick Examples to Get Python NumPy Array Shape

If you are in a hurry, below are some quick examples of how to get the shape of a Python NumPy array. Use the size property to get the length of the NumPy array.


# Below are quick examples

# Example 1: Creating 2 dimension array
arr = np.array([[3, 6, 7, 9], [2, 4, 6, 8]])
print(arr.shape)

# Example 2: Creating 3 dimension array
arr = np.array([[[2, 3],[3, 4]],[[5, 6], [8, 9]]])
print(arr.shape)

# Example 3: Using Multi dimension
arr = np.array([1, 3, 5, 7, 9], ndmin=6)
print('Shape of array :', arr.shape)

2. Get NumPy Array shape

Use ndarray.shape to get the shape of the NumPy array. This returns a tuple with each index having the number of corresponding elements. The below examples return (2,4) and (2,2,2) which means that the arr has 2 dimensions and each dimension has 4 elements (2 rows & 4 columns). Similarly, arr1 has 3 dimensions and each dimension has 2 rows and 2 columns.


import numpy as np

# Creating a 2 dimensions array
arr = np.array([[3, 6, 7, 9], [2, 4, 6, 8]])
print(arr.shape)

# Creating a 3 dimensions array
arr1 = np.array([[[2, 3],[3, 4]],[[5, 6], [8, 9]]])
print(arr1.shape)

Yields below output.


# Output
(2, 4)
(2, 2, 2)

3. Get the Shape of a Multi-Dimensional Array

Create an array using np.array() with 6 dimensions using ndmin param with values 1,3,5,7,9. This creates and 6-dimensional NumPy array. Let’s run a shape property on this and validate the result.


# Use shape of Multi-Dimensional Array
arr = np.array([1, 3, 5, 7, 9], ndmin=6)
print(arr)
print('Shape of array :', arr.shape)

Yields below output.


# Output
[[[[[[1 3 5 7 9]]]]]]
Shape of array : (1, 1, 1, 1, 1, 5)

4. Conclusion

In this article, I have explained how to get the shape of a Python NumPy array by using numpy.ndarray.shape property with examples. This returns a tuple with the number of rows and columns in an array. The array shape can be defined as the number of elements in each dimension and dimension is defined as a number of indices or subscripts, that can specify an individual element of an array.

Happy Learning!!

References

Leave a Reply