NumPy: Count number of occurrences of each value in a given array of non-negative integers
Write a Python program to count number of occurrences of each value in a given array of non-negative integers.
Note: bincount() function count number of occurrences of each value in an array of non-negative integers in the range of the array between the minimum and maximum values including the values that did not occur.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating a Python list
array1 = [0, 1, 6, 1, 4, 1, 2, 2, 7]
# Displaying the original array
print("Original array:")
print(array1)
# Calculating the number of occurrences of each value in the array
print("Number of occurrences of each value in array: ")
print(np.bincount(array1))
Sample Output:
Original array: [0, 1, 6, 1, 4, 1, 2, 2, 7] Number of occurrences of each value in array: [1 3 2 0 1 0 1 1]
Explanation:
In the above exercise –
array1 = [0, 1, 6, 1, 4, 1, 2, 2, 7]: Creates a 1-dimensional Python list array1 containing integer values.
print(np.bincount(array1)): Computes the frequency of occurrences of each integer value in array1. The output of np.bincount() is an array of length k+1, where k is the maximum value in the input array. Each element i in the output array indicates the number of times that i appears in the input array.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics