Array Shape – NumPy

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 of. ndarray.shape returns a tuple with dimensions along all the axis of the numpy array.

Examples

1. Get shape of multi-dimensional NumPy array

In the following example, we have initialized a multi-dimensional numpy array. Of course, we know the shape of the array by its definition. But, we will use 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)
Run Code Copy

Output

(2, 2, 4)

2. Get shape of 2D NumPy array

In the following example, we will create a 2D numpy array and find its shape. There are two rows and four columns. So, we should get a tuple of (2, 4). Let us see.

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)
Run Code Copy

Output

(2, 4)

3. Get shape of 1-Dimensional NumPy array

In the following example, we take a one-dimensional numpy array, and find its 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)
Run Code Copy

There are four elements, and of course, the shape should be a tuple with 4.

Output

(4,)

Summary

In this Numpy Tutorial, we learned how to get the shape of a given numpy array as a tuple.

Related Tutorials

Code copied to clipboard successfully 👍