How to return the shape of an array in Python
Overview
The ma.shape() method in the NumPy module in Python is used to obtain the shape of a given array.
The shape of an array is the number of elements found in each axis (rows and columns) of the array. For example, an array with a shape, (2, 3), means that the array has 2 rows that contain 3 elements each.
Syntax
The ma.shape() function takes the syntax below:
ma.shape(obj)
Parameter value
The ma.shape() function takes a single parameter value, obj, which represents the input array.
Return value
The ma.shape() function returns the shape of the input array.
Example
Let's look at the code below:
import numpy as npimport numpy.ma as ma# creating an arraya = np.array([1, 2, 3, 4, 5, 6])b = np.array([[1, 2, 3], [4, 5, 6]])# implementing the ma.shape() methodc = ma.shape(a)d = ma.shape(b)print(a)print("This is the shape of array a: ", c)print(b)print("This is the shape of array b: ", d)
Explanation
Line 1: We import the
numpymodule.Line 2: We import the
numpy.mamodule.Lines 4 and 5: We create the input arrays,
aandb, using thearray()function.Lines 8 and 9: We apply the
ma.shape()function onaandband pass their respective results tocandd.Lines 11 and 15: We return the arrays
aandband their respective shapescandd.