0
0
NumPydata~5 mins

Counting with boolean arrays in NumPy

Choose your learning style9 modes available
Introduction

Counting with boolean arrays helps you quickly find how many items meet a condition. It is simple and fast.

You want to count how many students passed an exam from their scores.
You need to find how many products are in stock from a list of inventory statuses.
You want to know how many days were rainy from a weather data array.
You want to count how many emails are unread in your inbox data.
Syntax
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.

Examples
Counts how many scores are 60 or more.
NumPy
import numpy as np

scores = np.array([70, 85, 40, 90])
passed = scores >= 60
count_passed = np.sum(passed)
print(count_passed)
Counts True in an empty array, result is 0.
NumPy
import numpy as np

empty_array = np.array([])
boolean_empty = empty_array > 0
count_empty = np.sum(boolean_empty)
print(count_empty)
Counts True when only one element is checked.
NumPy
import numpy as np

single_value = np.array([100])
boolean_single = single_value < 50
count_single = np.sum(boolean_single)
print(count_single)
Counts True when the condition matches the last element.
NumPy
import numpy as np

values = np.array([10, 20, 30, 40])
boolean_end = values == 40
count_end = np.sum(boolean_end)
print(count_end)
Sample Program

This program creates an array of temperatures. It finds which days are hotter than 25 degrees and counts them.

NumPy
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)
OutputSuccess
Important Notes

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.

Summary

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.