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 occurrences of a specified item in a given NumPy array.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Creating a NumPy array 'nums' containing integers
nums = np.array([10, 20, 20, 20, 20, 0, 20, 30, 30, 30, 0, 0, 20, 20, 0])
# Printing a message indicating the original array will be displayed
print("Original array:")
# Printing the original array 'nums' with its elements
print(nums)
# Counting the occurrences of specific values in the array 'nums'
# Printing the count of occurrences for the values 10, 20, 30, and 0 using np.count_nonzero() with boolean conditionals
print(np.count_nonzero(nums == 10)) # Count of occurrences of value 10
print(np.count_nonzero(nums == 20)) # Count of occurrences of value 20
print(np.count_nonzero(nums == 30)) # Count of occurrences of value 30
print(np.count_nonzero(nums == 0)) # Count of occurrences of value 0
Sample Output:
Original array: [10 20 20 20 20 0 20 30 30 30 0 0 20 20 0] 1 7 3 4
Explanation:
In the above code -
nums = np.array([...]): This line creates a NumPy array named 'nums' containing a sequence of integer values.
np.count_nonzero(nums == 10) - Count the number of occurrences of the value 10 in the 'nums' array. The expression nums == 10 creates a boolean array where each element is True if the corresponding element in 'nums' is equal to 10 and False otherwise. Then, np.count_nonzero counts the number of True values in the boolean array, which is equal to the number of occurrences of the value 10.
The next three lines repeat the same process for counting the occurrences of the values 20, 30, and 0 in the 'nums' array.
Pictorial Presentation:
Python-Numpy Code Editor:
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 Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-106.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics