How to return the number of elements in a given axis of an array
Overview
The ma.size() method belongs to the numpy.ma module in Python. And it is used to obtain the number of elements along a given axis of an array.
Syntax
The ma.size() method takes the syntax below:
ma.size(obj, axis=None)
Parameters
The ma.size() function takes the following parameter values:
obj: The input array. It is a required parameter.axis: The axis along which the counts of the elements are taken. It is an optional parameter.
Return value
The ma.size() function returns the size (number of elements) of the specified axis of a given 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.size() methodc = ma.size(a)d = ma.size(b)print(a)print("The size of array a is: ", c)print(b)print("The size of array b is: ", 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 implement the
ma.size()function onaandband pass their respective results tocandd.Lines 11 to 15: We return the arrays
aandband their respective shapes,candd.