0
0
NumPydata~20 mins

np.count_nonzero() for counting in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Count Nonzero Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A0
B4
C7
D3
Attempts:
2 left
💡 Hint
Count how many numbers are not zero in the array.
data_output
intermediate
2: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)
A[2 2 2]
B[3 3 3]
C[1 2 2]
D[2 1 1]
Attempts:
2 left
💡 Hint
Count non-zero values in each column (axis 0).
🔧 Debug
advanced
2: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)
AAxisError: axis 1 is out of bounds for array of dimension 1
BTypeError: '>' not supported between instances of 'int' and 'int'
CValueError: operands could not be broadcast together
DNo error, output is 2
Attempts:
2 left
💡 Hint
Check the dimension of the array and the axis used.
🚀 Application
advanced
2: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)
A4
B3
C5
D6
Attempts:
2 left
💡 Hint
Count how many True values are in the mask.
🧠 Conceptual
expert
2: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)
ARaises TypeError
B3
C2
D4
Attempts:
2 left
💡 Hint
Remember that NaN is treated as a non-zero value in numpy.