NumPy Array Shape

M.Ramya

 Shape of an Array

The shape of an array refers to the number of elements it contains along each dimension.

Getting the Shape of an Array

In NumPy, arrays have an attribute called shape that returns a tuple representing the size of the array in each dimension. Each value in the tuple corresponds to the number of elements along that dimension.

Program:

Print the shape of a 2-D array:

import numpy as np

arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

print(arr.shape)

Output:

(2,4)

Program:

Create an array with 5 dimensions using ndmin and verify that the last dimension has size 4:

import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)

print('Shape of array:', arr.shape)

In this example, a vector with values [1, 2, 3, 4] is created with 5 dimensions. The shape shows that the size of the last dimension is 4.

Output:

[[[[[1 2 3 4]]]]]

shape of array:(1,1,1,1,4)

What Does the Shape Tuple Represent?

Each integer in the shape tuple indicates the number of elements along that specific dimension.

In the example above, the value at index 4 in the shape tuple is 4. This means the 5th dimension (since indexing starts from 0, index 4 corresponds to the 5th dimension) contains 4 elements.
























Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send