0
0
NumPydata~20 mins

Counting with boolean arrays in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Boolean Counting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Counting True values in a boolean NumPy array
What is the output of this code snippet that counts True values in a boolean NumPy array?
NumPy
import numpy as np
arr = np.array([True, False, True, True, False])
count = np.sum(arr)
print(count)
A4
B2
C5
D3
Attempts:
2 left
💡 Hint
Remember that True is treated as 1 and False as 0 in NumPy when summing.
data_output
intermediate
2:00remaining
Counting True values along an axis in a 2D boolean array
Given this 2D boolean array, what is the output of counting True values along axis 1?
NumPy
import numpy as np
arr = np.array([[True, False, True], [False, False, True], [True, True, True]])
counts = np.sum(arr, axis=1)
print(counts)
A[1 2 3]
B[2 1 3]
C[3 1 2]
D[2 2 2]
Attempts:
2 left
💡 Hint
Sum along axis 1 means count True values in each row.
🔧 Debug
advanced
2:00remaining
Identify the error in counting True values with incorrect axis
What error does this code raise when trying to count True values along axis 2 in a 2D boolean array?
NumPy
import numpy as np
arr = np.array([[True, False], [False, True]])
count = np.sum(arr, axis=2)
print(count)
AAxisError: axis 2 is out of bounds for array of dimension 2
BTypeError: unsupported operand type(s) for +: 'bool' and 'int'
CValueError: operands could not be broadcast together
DNo error, output is [1 1]
Attempts:
2 left
💡 Hint
Check the dimensions of the array and the axis argument.
🚀 Application
advanced
2:00remaining
Counting values greater than a threshold using boolean arrays
Given a NumPy array of numbers, which option correctly counts how many values are greater than 10?
NumPy
import numpy as np
arr = np.array([5, 12, 7, 20, 15])
count = ???
print(count)
Anp.sum(arr > 10)
Bnp.sum(arr >= 10)
Cnp.count_nonzero(arr < 10)
Dnp.count_nonzero(arr == 10)
Attempts:
2 left
💡 Hint
Create a boolean array where values are greater than 10, then sum True values.
🧠 Conceptual
expert
2:00remaining
Understanding boolean array counting with np.count_nonzero vs np.sum
Which statement best describes the difference between np.count_nonzero(boolean_array) and np.sum(boolean_array) when counting True values?
Anp.count_nonzero counts False values; np.sum counts True values.
Bnp.count_nonzero returns the total number of elements; np.sum counts only True values.
Cnp.count_nonzero counts True values directly; np.sum treats True as 1 and sums them, both give the same result for boolean arrays.
Dnp.count_nonzero returns a boolean array; np.sum returns an integer count.
Attempts:
2 left
💡 Hint
Think about how True and False are treated in NumPy arithmetic and counting.