The shape of an array can be defined as the number of elements in each dimension. Dimension is the number of indices or subscripts, that we require in order to specify an individual element of an array.
How can we get the Shape of an Array?
In NumPy, we will use an attribute called shape which returns atuple, the elements of the tuple give the lengths of the corresponding array dimensions.
Syntax: numpy.shape(array_name)
Parameters:Array is passed as a Parameter.
Return:A tuple whose elements give the lengths of the corresponding array dimensions.
Shape Manipulation in NumPy
Below are some examples by which we can understand about shape manipulation inNumPyinPython:
Example 1: Shape of Arrays
Printing the shape of the multidimensional array. In this example, two NumPy arraysarr1
andarr2
are created, representing a 2D array and a 3D array, respectively. The shape of each array is printed, revealing their dimensions and sizes along each dimension.
Python3importnumpyasnpy# creating a 2-d arrayarr1=npy.array([[1,3,5,7],[2,4,6,8]])# creating a 3-d arrayarr2=npy.array([[[1,2],[3,4]],[[5,6],[7,8]]])print(arr1.shape)print(arr2.shape)
Output:
(2, 4)
(2, 2,2)
Example 2: Shape of Array Using ndim
In this example, we are creating an array usingndminusing a vector with values 2,4,6,8,10 and verifying the value of last dimension.
python3importnumpyasnpy# creating an array of 6 dimension# using ndimarr=npy.array([2,4,6,8,10],ndmin=6)# printing arrayprint(arr)# verifying the value of last dimension# as 5print('shape of an array :',arr.shape)
Output:
[[[[[[ 2 4 6 8 10]]]]]]
shape of an array : (1, 1, 1, 1, 1, 5)
Example 3: Shape of Array of Tuples
In this example, we'll create aNumPy array where each element is a tuple. We'll also demonstrate how to determine the shape of such an array.
Python3importnumpyasnp# Create an array of tuplesarray_of_tuples=np.array([(1,2),(3,4),(5,6),(7,8)])# Display the arrayprint("Array of Tuples:")print(array_of_tuples)# Determine and display the shapeshape=array_of_tuples.shapeprint("\nShape of Array:",shape)
Output:
Array of Tuples:
[[1 2]
[3 4]
[5 6]
[7 8]]Shape of Array: (4, 2)