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.
Jump into concepts and practice - no test required
import numpy as np arr = np.array([1, 3, 5, 2, 4]) bool_arr = arr > 3 count = bool_arr.sum() print(count)
| Step | Action | Variable | Value | Explanation |
|---|---|---|---|---|
| 1 | Create array | arr | [1 3 5 2 4] | Original numeric array |
| 2 | Apply condition arr > 3 | bool_arr | [False False True False True] | Boolean array where True means element > 3 |
| 3 | Count True values | count | 2 | Sum counts True as 1, so total is 2 |
| 4 | Print count | output | 2 | Output shows how many elements are > 3 |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| arr | None | [1 3 5 2 4] | [1 3 5 2 4] | [1 3 5 2 4] | [1 3 5 2 4] |
| bool_arr | None | None | [False False True False True] | [False False True False True] | [False False True False True] |
| count | None | None | None | 2 | 2 |
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
arr = np.array([True, False, True])arr.sum()?[True, False, True] is 1 + 0 + 1 = 2.arr = np.array([1, 2, 3, 4]) are greater than 2 using boolean arrays?arr > 2 creates a boolean array: [False, False, True, True].(arr > 2).sum().import numpy as np arr = np.array([5, 3, 8, 1, 6]) count = (arr % 2 == 0).sum() print(count)
arr % 2 == 0 checks which elements are even: [False, False, True, False, True].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)
10.sum() is invalid because 10 is an integer, not an array.(arr < 10).sum().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?data > 5 creates a boolean array marking elements greater than 5.(data > 5).sum() to count all True values in the 2D array.