Bird
Raised Fist0
NumPydata~5 mins

Counting with boolean arrays in NumPy

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What does summing a boolean array in NumPy do?
arr = np.array([True, False, True])
What is arr.sum()?
easy
A. Returns the length of the array
B. Counts how many False values are in the array
C. Counts how many True values are in the array
D. Returns an error because booleans cannot be summed

Solution

  1. Step 1: Understand boolean values in NumPy

    In NumPy, True is treated as 1 and False as 0 when summed.
  2. Step 2: Sum the boolean array

    Summing [True, False, True] is 1 + 0 + 1 = 2.
  3. Final Answer:

    Counts how many True values are in the array -> Option C
  4. Quick Check:

    True count = 2 [OK]
Hint: Sum boolean arrays to count True values quickly [OK]
Common Mistakes:
  • Thinking sum counts False values
  • Believing sum returns array length
  • Expecting an error when summing booleans
2. Which of the following is the correct syntax to count how many elements in arr = np.array([1, 2, 3, 4]) are greater than 2 using boolean arrays?
easy
A. (arr > 2).sum()
B. arr > 2.sum()
C. arr.sum() > 2
D. arr > 2).sum()

Solution

  1. Step 1: Create boolean array for condition

    arr > 2 creates a boolean array: [False, False, True, True].
  2. Step 2: Sum the boolean array correctly

    We must sum the boolean array, so use parentheses: (arr > 2).sum().
  3. Final Answer:

    (arr > 2).sum() -> Option A
  4. Quick Check:

    Correct syntax uses parentheses [OK]
Hint: Use parentheses around condition before sum() [OK]
Common Mistakes:
  • Missing parentheses causing wrong order
  • Using sum() on condition without parentheses
  • Confusing comparison and sum order
3. What is the output of this code?
import numpy as np
arr = np.array([5, 3, 8, 1, 6])
count = (arr % 2 == 0).sum()
print(count)
medium
A. 3
B. 0
C. 5
D. 2

Solution

  1. Step 1: Create boolean array for even numbers

    arr % 2 == 0 checks which elements are even: [False, False, True, False, True].
  2. Step 2: Sum True values to count evens

    Sum is 0 + 0 + 1 + 0 + 1 = 2.
  3. Final Answer:

    2 -> Option D
  4. Quick Check:

    Count of even numbers = 2 [OK]
Hint: Sum boolean condition to count matching elements [OK]
Common Mistakes:
  • Counting odd numbers instead
  • Forgetting to use parentheses
  • Misunderstanding modulo operator
4. The code below is intended to count how many values in arr are less than 10, but it raises an error. What is the error and how to fix it?
import numpy as np
arr = np.array([7, 12, 5, 20])
count = arr < 10.sum()
print(count)
medium
A. Error: Missing import statement
B. Error: 10.sum() is invalid; fix by using (arr < 10).sum()
C. No error; output is boolean array
D. Error: arr < 10 is invalid; fix by using arr.sum() < 10

Solution

  1. Step 1: Identify the error in expression

    10.sum() is invalid because 10 is an integer, not an array.
  2. Step 2: Correct the syntax to sum boolean array

    Use parentheses to sum the boolean array: (arr < 10).sum().
  3. Final Answer:

    Error: 10.sum() is invalid; fix by using (arr < 10).sum() -> Option B
  4. Quick Check:

    Parentheses needed before sum() [OK]
Hint: Always put parentheses around condition before sum() [OK]
Common Mistakes:
  • Calling sum() on number instead of boolean array
  • Confusing comparison and sum order
  • Ignoring error message details
5. Given a 2D NumPy array data = np.array([[3, 7, 2], [5, 1, 8], [6, 4, 9]]), how can you count how many elements are greater than 5 across the entire array?
hard
A. (data > 5).sum()
B. data[data > 5].count()
C. data.sum() > 5
D. np.count(data > 5)

Solution

  1. Step 1: Create boolean array for elements > 5

    data > 5 creates a boolean array marking elements greater than 5.
  2. Step 2: Sum True values to count elements

    Use (data > 5).sum() to count all True values in the 2D array.
  3. Final Answer:

    (data > 5).sum() -> Option A
  4. Quick Check:

    Sum boolean mask counts elements > 5 [OK]
Hint: Sum boolean mask over entire array to count matches [OK]
Common Mistakes:
  • Using sum() on data directly
  • Trying to use count() method on NumPy array
  • Using non-existent np.count() function