w3resource

NumPy: Count number of occurrences of each value in a given array of non-negative integers

NumPy Statistics: Exercise-13 with Solution

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:

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

Previous: Write a Python NumPy program to compute the weighted average along the specified axis of a given flattened array.
Next: Write a NumPy program to compute the histogram of nums against the bins.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/python-exercises/numpy/python-numpy-stat-exercise-13.php