Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to count the non-masked elements of an array in Python

Onyejiaku Theophilus Chidalu

Overview

The numpy.ma.count() method in Python counts the non-masked elements of an array along a given axis.

Syntax

The ma.count() method takes the syntax below:

ma.count(self, axis=None, keepdims=<no value>)
The syntax for the ma.count() function in Python

Parameter value

The ma.count() takes the following parameter values:

  • axis: This is the axis on which the count is done. It is an optional parameter.
  • keepdims: This takes a Boolean value indicating whether or not the axes reduced are left in the result as dimensions with size one. This is an optional parameter.

Return value

The ma.count()method returns an array having the same shape as the input array, with the specified axis removed.

Example

import numpy.ma as ma
# creating a masked array
a = ma.arange(8).reshape(4,2)

# masking the elements in the third row
a[2, :] = ma.masked

# taking counts of non-masked elements along rows
b = a.count(axis=1)

# taking count of non-masked elements along columns
c = a.count(axis=0)

print(a)
print("Taking count along row: ", b)
print("Taking count along columns: ", c)
Implementing the ma.count() function

Explanation

  • Line 1: We import the numpy.ma module.
  • Line 3: We create a masked input array, a.
  • Line 6: We mask the elements present in the input array's third row.
  • Line 9: We take count of the non-masked elements in axis 1 (rows) of the input array. The result is assigned to a variable, b.
  • Line 12: We take count of the non-masked elements in axis 0 (columns) of the input array. The result is assigned to a variable, c.
  • Line 14-16: We print the input array, a, and the arrays b and c.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring