Challenge - 5 Problems
Count Nonzero Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Counting non-zero elements in a 1D array
What is the output of this code snippet using
np.count_nonzero()?NumPy
import numpy as np arr = np.array([0, 1, 2, 0, 3, 0, 4]) result = np.count_nonzero(arr) print(result)
Attempts:
2 left
💡 Hint
Count how many numbers are not zero in the array.
✗ Incorrect
The array has four non-zero numbers: 1, 2, 3, and 4. So, np.count_nonzero returns 4.
❓ data_output
intermediate2:00remaining
Counting non-zero elements along an axis in 2D array
What is the output of
np.count_nonzero() when counting non-zero elements along axis 0 in this 2D array?NumPy
import numpy as np arr = np.array([[0, 1, 2], [3, 0, 0], [4, 5, 6]]) result = np.count_nonzero(arr, axis=0) print(result)
Attempts:
2 left
💡 Hint
Count non-zero values in each column (axis 0).
✗ Incorrect
Column-wise counts: first column has 2 non-zero (3,4), second column 2 non-zero (1,5), third column 2 non-zero (2,6).
🔧 Debug
advanced2:00remaining
Identify the error in using np.count_nonzero with a condition
What error does this code raise?
NumPy
import numpy as np arr = np.array([1, 2, 3, 4, 5]) result = np.count_nonzero(arr > 3, axis=1) print(result)
Attempts:
2 left
💡 Hint
Check the dimension of the array and the axis used.
✗ Incorrect
The array is 1D, so axis=1 is invalid and causes AxisError.
🚀 Application
advanced2:00remaining
Using np.count_nonzero to count True values in a boolean mask
Given this boolean mask, what does
np.count_nonzero(mask) return?NumPy
import numpy as np mask = np.array([[True, False, True], [False, False, True], [True, True, False]]) result = np.count_nonzero(mask) print(result)
Attempts:
2 left
💡 Hint
Count how many True values are in the mask.
✗ Incorrect
There are five True values in the mask array.
🧠 Conceptual
expert2:00remaining
Effect of np.count_nonzero on arrays with NaN values
What is the output of
np.count_nonzero() when applied to this array containing NaN values?NumPy
import numpy as np arr = np.array([0, np.nan, 1, 2, np.nan, 0]) result = np.count_nonzero(arr) print(result)
Attempts:
2 left
💡 Hint
Remember that NaN is treated as a non-zero value in numpy.
✗ Incorrect
NaN is not zero, so it counts as non-zero. The non-zero elements are the two np.nan, 1, and 2, totaling 4.