Counting with boolean arrays helps you quickly find how many items meet a condition. It is simple and fast.
Counting with boolean arrays in NumPy
import numpy as np # Create a boolean array by applying a condition boolean_array = (array > value) # Count True values using np.sum count_true = np.sum(boolean_array)
Boolean arrays contain only True or False values.
True counts as 1 and False counts as 0 when summed.
import numpy as np scores = np.array([70, 85, 40, 90]) passed = scores >= 60 count_passed = np.sum(passed) print(count_passed)
import numpy as np empty_array = np.array([]) boolean_empty = empty_array > 0 count_empty = np.sum(boolean_empty) print(count_empty)
import numpy as np single_value = np.array([100]) boolean_single = single_value < 50 count_single = np.sum(boolean_single) print(count_single)
import numpy as np values = np.array([10, 20, 30, 40]) boolean_end = values == 40 count_end = np.sum(boolean_end) print(count_end)
This program creates an array of temperatures. It finds which days are hotter than 25 degrees and counts them.
import numpy as np # Create an array of temperatures temperatures = np.array([22, 35, 18, 27, 30, 15, 40]) # Condition: temperatures above 25 degrees hot_days = temperatures > 25 # Print boolean array print('Hot days boolean array:', hot_days) # Count how many days are hot count_hot_days = np.sum(hot_days) print('Number of hot days:', count_hot_days)
Time complexity is O(n), where n is the number of elements in the array.
Space complexity is O(n) for the boolean array created by the condition.
Common mistake: forgetting that np.sum counts True as 1 and False as 0, so you must use a boolean array.
Use counting with boolean arrays when you want a quick count of items meeting a condition instead of looping manually.
Boolean arrays hold True/False values from conditions.
Summing boolean arrays counts how many True values there are.
This method is fast and easy for counting items that meet conditions.