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.
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