# Count the number of masked elements in Numpy

NumpyServer Side ProgrammingProgramming

To count the number of masked elements, use the ma.MaskedArray.count_masked() method in Python Numpy. The method returns the total number of masked elements (axis=None) or the number of masked elements along each slice of the given axis.

The axis parameter is the axis along which to count. If None (default), a flattened version of the array is used.

## Steps

At first, import the required library −

import numpy as np
import numpy.ma as ma

Creating a 4x4 array with int elements using the numpy.arange() method −

arr = np.arange(16).reshape((4,4))
print("Array...\n", arr)
print("\nArray type...\n", arr.dtype)

Get the dimensions of the Array −

print("\nArray Dimensions...\n",arr.ndim)
print("\nOur Array type...\n", arr.dtype)

Get the shape of the Array −

print("\nOur Masked Array Shape...\n",arr.shape)


Get the number of elements of the Array −

print("\nElements in the Masked Array...\n",arr.size)

arr = ma.array(arr)

arr[3, 3] = ma.masked

print("\nResult (number of masked elements)...\n",ma.count_masked(arr))


## Example

# Python ma.MaskedArray - Count the number of masked elements

import numpy as np
import numpy.ma as ma

# Creating a 4x4 array with int elements using the numpy.arange() method
arr = np.arange(16).reshape((4,4))
print("Array...\n", arr)
print("\nArray type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nArray Dimensions...\n",arr.ndim)
print("\nOur Array type...\n", arr.dtype)

# Get the shape of the Array

# Get the number of elements of the Array

arr = ma.array(arr)

print("\nResult (number of masked elements)...\n",ma.count_masked(arr))

## Output

Array...
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

Array type...
int64

Array Dimensions...
2

Our Array type...
int64

7