Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

function
numpy
python
communitycreator

How to return the number of elements in a given axis of an array

Onyejiaku Theophilus Chidalu

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)
Syntax for the ma.size() method

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 np
import numpy.ma as ma
# creating an array 
a = np.array([1, 2, 3, 4, 5, 6])
b = np.array([[1, 2, 3], [4, 5, 6]])

# implementing the ma.size() method
c = 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)
Implementing the ma.size() method

Explanation

  • Line 1: We import the numpy module.
  • Line 2: We import the numpy.ma module.
  • Lines 4 and 5: We create the input arrays, a and b, using the array() function.
  • Lines 8 and 9: We implement the ma.size() function on a and b and pass their respective results to c and d.
  • Lines 11 to 15: We return the arrays a and b and their respective shapes, c and d.

RELATED TAGS

function
numpy
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring