Bird
Raised Fist0
NumPydata~10 mins

Counting with boolean arrays in NumPy - Step-by-Step Execution

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
Concept Flow - Counting with boolean arrays
Create boolean array
↓
Apply condition to get boolean array
↓
Count True values using sum()
↓
Output count
We create a boolean array by applying a condition, then count how many True values it has using sum.
Execution Sample
NumPy
import numpy as np
arr = np.array([1, 3, 5, 2, 4])
bool_arr = arr > 3
count = bool_arr.sum()
print(count)
This code counts how many numbers in the array are greater than 3.
Execution Table
StepActionVariableValueExplanation
1Create arrayarr[1 3 5 2 4]Original numeric array
2Apply condition arr > 3bool_arr[False False True False True]Boolean array where True means element > 3
3Count True valuescount2Sum counts True as 1, so total is 2
4Print countoutput2Output shows how many elements are > 3
💡 All steps done, count of True values calculated and printed
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
arrNone[1 3 5 2 4][1 3 5 2 4][1 3 5 2 4][1 3 5 2 4]
bool_arrNoneNone[False False True False True][False False True False True][False False True False True]
countNoneNoneNone22
Key Moments - 3 Insights
Why does summing a boolean array count True values?
In numpy, True is treated as 1 and False as 0 when summed, so sum counts how many True values exist (see execution_table step 3).
What if the condition returns no True values?
Then the boolean array has all False, sum returns 0, meaning no elements met the condition (not shown here but same logic applies).
Can we count False values the same way?
Yes, by summing the negation (~bool_arr) or using (bool_arr == False), sum counts False values.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of bool_arr after step 2?
A[False True False True False]
B[False False True False True]
C[True True False True False]
D[True False True False True]
💡 Hint
Check the 'Value' column for bool_arr at step 2 in execution_table.
At which step is the count of True values calculated?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look for the step where 'count' variable gets a numeric value in execution_table.
If the array was arr = np.array([0, 1, 2]), what would count be after applying arr > 3?
A1
B3
C0
D2
💡 Hint
Refer to how sum counts True values; none of these numbers are > 3, so sum is zero.
Concept Snapshot
Counting with boolean arrays:
- Apply a condition to get a boolean array (True/False)
- True counts as 1, False as 0
- Use sum() on boolean array to count True values
- Useful for quick counts of elements meeting a condition
Full Transcript
We start by creating a numpy array of numbers. Then we apply a condition (like greater than 3) to get a boolean array where each element is True if it meets the condition, False otherwise. Next, we sum the boolean array. Since True counts as 1 and False as 0, the sum gives the count of elements meeting the condition. Finally, we print this count. This method is simple and fast for counting with conditions in numpy.

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