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:

import numpy as np
array1 = [0, 1, 6, 1, 4, 1, 2, 2, 7] 
print("Original array:")
print(array1)
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]

Python 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 Python skills with w3resource's quiz



Python: Tips of the Day

Python: Use Enumerate() In for Loops

>>> students = ('John', 'Mary',  'Mike')
>>> for i, student in enumerate(students):
  ...     print(f'Iteration:  {i}, Student: {student}')
  ... 
Iteration: 0, Student: John
Iteration: 1, Student: Mary
Iteration: 2, Student: Mike
>>> for i, student in enumerate(students,  35001):
  ...      print(f'Student Name: {student}, Student ID #: {i}')
  ... 
Student Name: John, Student ID #: 35001
Student Name: Mary, Student ID #: 35002
Student Name: Mike, Student ID #: 35003