Instagram
youtube
Facebook
Twitter

Count True Values in a Boolean Mask in NumPy

A Count True Values in a Boolean Mask in NumPy?
Code Explanation:
Library Import:
numpy is imported as np to work with arrays and perform numerical operations.
Array Creation: A NumPy array arr is created with integer elements.
Boolean Mask: mask = arr > 5 creates a boolean array where elements greater than 5 are marked as True.
Counting Trues: np.sum(mask) adds up the number of True values in the mask (since True is treated as 1).
Store Result: The count of True values is stored in the variable count.
Display Output: print(count) prints the number of True values: 2.

 

Program:

import numpy as np

arr = np.array([3, 6, 9, 2])

mask = arr > 5

count = np.sum(mask)

print(count)