Bird
Raised Fist0
NumPydata~20 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1.

What does the np.count_nonzero() function do in NumPy?

easy
A. Calculates the sum of all elements in an array
B. Returns the shape of the array
C. Finds the maximum value in an array
D. Counts how many elements in an array are not zero

Solution

  1. Step 1: Understand the function purpose

    np.count_nonzero() counts elements that are not zero in the array.
  2. Step 2: Compare with other options

    Other options describe different functions like sum, max, or shape, which are not what np.count_nonzero() does.
  3. Final Answer:

    Counts how many elements in an array are not zero -> Option D
  4. Quick Check:

    Counting non-zero elements = Counts how many elements are not zero [OK]
Hint: Remember: count_nonzero counts non-zero values only [OK]
Common Mistakes:
  • Confusing count_nonzero with sum or max functions
  • Thinking it returns the array shape
  • Assuming it counts zero elements
2.

Which of the following is the correct syntax to count non-zero elements in a NumPy array arr?

arr = np.array([1, 0, 3, 0, 5])
easy
A. np.count_nonzero = arr
B. np.count_nonzero(arr)
C. arr.count_nonzero()
D. np.count(arr != 0)

Solution

  1. Step 1: Identify correct function usage

    The function np.count_nonzero() is called with the array as argument: np.count_nonzero(arr).
  2. Step 2: Check other options for errors

    np.count_nonzero = arr tries to assign instead of call; arr.count_nonzero() uses method not available on array; np.count(arr != 0) uses a non-existent function np.count().
  3. Final Answer:

    np.count_nonzero(arr) -> Option B
  4. Quick Check:

    Correct syntax is np.count_nonzero(array) [OK]
Hint: Use np.count_nonzero(array) to count non-zero values [OK]
Common Mistakes:
  • Using assignment instead of function call
  • Calling count_nonzero as a method on array
  • Using non-existent np.count function
3.

What is the output of the following code?

import numpy as np
arr = np.array([[0, 1, 2], [3, 0, 0], [4, 5, 6]])
count = np.count_nonzero(arr, axis=0)
print(count)
medium
A. [3 2 3]
B. [3 3 3]
C. [2 3 2]
D. [2 2 2]

Solution

  1. Step 1: Understand axis=0 counting

    Counting non-zero elements along columns (axis=0) means counting down each column.
  2. Step 2: Count non-zero per column

    Column 1: values [0,3,4] -> non-zero count = 2 (3 and 4)
    Column 2: values [1,0,5] -> non-zero count = 2 (1 and 5)
    Column 3: values [2,0,6] -> non-zero count = 2 (2 and 6)
  3. Final Answer:

    [3 2 3] -> Option A
  4. Quick Check:

    Count non-zero per column = [3 2 3] [OK]
Hint: axis=0 counts down columns, axis=1 counts across rows [OK]
Common Mistakes:
  • Counting zeros instead of non-zero
  • Confusing axis=0 with axis=1
  • Miscounting elements per column
4.

Find the error in this code snippet and choose the correct fix:

import numpy as np
arr = np.array([1, 0, 2, 0, 3])
count = np.count_nonzero(arr, axis=1)
print(count)
medium
A. Remove axis=1 because arr is 1D, use np.count_nonzero(arr) instead
B. Change axis=1 to axis=0 to fix the error
C. Use arr.count_nonzero() method instead
D. No error, code runs fine

Solution

  1. Step 1: Identify array dimension

    Array arr is 1D, so axis=1 is invalid (no second axis).
  2. Step 2: Correct function call

    Remove axis argument to count all non-zero elements: np.count_nonzero(arr).
  3. Final Answer:

    Remove axis=1 because arr is 1D, use np.count_nonzero(arr) instead -> Option A
  4. Quick Check:

    1D arrays have no axis=1, so omit axis [OK]
Hint: Check array shape before using axis in count_nonzero [OK]
Common Mistakes:
  • Using axis=1 on 1D arrays causes errors
  • Trying to call count_nonzero as array method
  • Assuming axis=0 fixes all axis errors
5.

You have a 2D NumPy array representing attendance (1 for present, 0 for absent) of 4 students over 5 days:

attendance = np.array([
  [1, 0, 1, 1, 0],
  [0, 0, 1, 0, 0],
  [1, 1, 1, 1, 1],
  [0, 0, 0, 0, 0]
])

Which code correctly counts how many days each student was present?

hard
A. np.sum(attendance, axis=0)
B. np.count_nonzero(attendance, axis=0)
C. np.count_nonzero(attendance, axis=1)
D. np.count_nonzero(attendance)

Solution

  1. Step 1: Understand data layout

    Rows represent students, columns represent days. Counting days present per student means counting non-zero per row (axis=1).
  2. Step 2: Choose correct axis

    Use np.count_nonzero(attendance, axis=1) to count non-zero values per student (row).
  3. Final Answer:

    np.count_nonzero(attendance, axis=1) -> Option C
  4. Quick Check:

    Count per row (student) = axis=1 [OK]
Hint: Count per student = count_nonzero with axis=1 [OK]
Common Mistakes:
  • Using axis=0 counts per day, not per student
  • Using np.sum instead of count_nonzero (works but different function)
  • Counting total non-zero without axis