NumPy ndarray.shape

The numpy.ndarray.shape attribute returns a tuple representing the dimensions of a NumPy array. It provides the number of elements along each axis of the array.

Syntax

</>
Copy
ndarray.shape

Return Value

Returns a tuple of integers representing the dimensions of the array. Each value in the tuple indicates the number of elements along a corresponding axis.


Examples

1. Checking the Shape of a 1D Array

In this example, we create a one-dimensional NumPy array and use the shape attribute to check its dimensions.

</>
Copy
import numpy as np

# Creating a 1D NumPy array with 5 elements
arr = np.array([10, 20, 30, 40, 50])

# Getting the shape of the array
shape = arr.shape

# Printing the shape
print("Shape of 1D array:", shape)

Output:

Shape of 1D array: (5,)

The output (5,) indicates that the array has a single dimension with 5 elements.

2. Checking the Shape of a 2D Array

Here, we create a two-dimensional (2D) array and check its shape.

</>
Copy
import numpy as np

# Creating a 2D NumPy array (matrix with 2 rows and 3 columns)
arr = np.array([[1, 2, 3], 
                [4, 5, 6]])

# Getting the shape of the array
shape = arr.shape

# Printing the shape
print("Shape of 2D array:", shape)

Output:

Shape of 2D array: (2, 3)

The output (2, 3) indicates that the array has 2 rows and 3 columns.

3. Checking the Shape of a 3D Array

This example demonstrates how the shape attribute works for a three-dimensional (3D) array.

</>
Copy
import numpy as np

# Creating a 3D NumPy array (with 2 matrices, each having 3 rows and 4 columns)
arr = np.array([[[1, 2, 3, 4], 
                 [5, 6, 7, 8], 
                 [9, 10, 11, 12]],

                [[13, 14, 15, 16], 
                 [17, 18, 19, 20], 
                 [21, 22, 23, 24]]])

# Getting the shape of the array
shape = arr.shape

# Printing the shape
print("Shape of 3D array:", shape)

Output:

Shape of 3D array: (2, 3, 4)

The output (2, 3, 4) means:

There are 2 matrices (first dimension).
Each matrix has 3 rows (second dimension).
Each row has 4 columns (third dimension).

4. Modifying the Shape of an ndarray

The shape attribute can also be modified to reshape an array, provided that the total number of elements remains the same.

</>
Copy
import numpy as np

# Creating a 1D NumPy array with 6 elements
arr = np.array([1, 2, 3, 4, 5, 6])

# Changing the shape of the array to (2, 3)
arr.shape = (2, 3)

# Printing the reshaped array and its new shape
print("Reshaped Array:\n", arr)
print("New Shape:", arr.shape)

Output:

Reshaped Array:
 [[1 2 3]
  [4 5 6]]
New Shape: (2, 3)

The array is successfully reshaped from a 1D array of 6 elements to a 2D array with 2 rows and 3 columns.