w3resource

NumPy: Count the occurrence of a specified item in a given NumPy array

NumPy: Array Object Exercise-106 with Solution

Write a NumPy program to count the occurrence of a specified item in a given NumPy array.

Sample Solution:

Python Code:

import numpy as np
nums = np.array([10, 20, 20, 20, 20, 0, 20, 30, 30, 30, 0, 0, 20, 20, 0])
print("Original array:")
print(nums)
print(np.count_nonzero(nums == 10))
print(np.count_nonzero(nums == 20))
print(np.count_nonzero(nums == 30))
print(np.count_nonzero(nums == 0))

Sample Output:

Original array:
[10 20 20 20 20  0 20 30 30 30  0  0 20 20  0]
1
7
3
4

Pictorial Presentation:

Python NumPy: Count the occurrence of a specified item in a given NumPy array

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to read a CSV data file and store records in an array.
Next: Write a NumPy program to calculate percentiles for a sequence or single-dimensional NumPy array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}