NumPy bincount() method with examples I Python

Hello everyone, in this tutorial, we will learn how to implement method the NumPy bincount() method in Python. Please go through this tutorial carefully for better understanding and further implementation of the numpy.bincount().

This method is used to count the frequency of each element in a NumPy array of non-negative integers. It stores the count of the element as its index in the frequency array or bin. So each bin value is the occurrence of its index and hence you can set the bin size accordingly. The bin size will always be equal to the largest element in NumPy array + 1. It is very useful for counting large data or records.

So,

sizeof(bin) = max(array) +1

Syntax :

freqbin = np.bincount(array_name)

Hence it returns the array or you can say frequency bin.

Example :

import numpy as np
arr = np.array([1,2,4,9,8,6,7,5])
freqbin = np.bincount(arr)
print(arr)
print(len(freqbin))
Output: [0,1,1,0,1,1,1,1,1,1]
        10      #sizeofbin

 

Addition using NumPy bincount() method

We can also add two arrays i.e. array with weighted array as per the element’s index using numpy.bincount() method in Python.

Syntax :

numpy.bincount( array, weighted_array)

Hence it returns the array or list of elements after the summation of the weights of the corresponding index. Hence the size of the bin will be the size of the first argument or non-weighted array + 1.

       sizeof(bin) = max(non-weighted_arrya) + 1

Example:

import numpy as np
a1 = np.array([1,2,1,2,3,4,1,3,2]    #non-weighted array
a2 = np.array([5,6,7,3,4,9,8,11,10]   #weighted array
sum1 = np.bincount(a1,a2)
print("Bin after the summation is :\n",sum1)

 

Output -> Bin after the summation is :
          [0. , 20. , 19. , 15. , 9.]

Explanation:

The element corresponding to the index will be added, so the elements in the index are given as:

Index 0 corresponding elements  = 0, Index 1 corresponding elements = 5+7+8 = 20, Index 2 corresponding elements = 6+3+10 = 19, Index 3 corresponding elements = 4+11 = 15, Index 4 corresponding elements = 9.

 

There are various approaches to the same but I have given you the simplest approach to use numpy.bincount() method and its various methods.

I hope you would be benefited with this tutorial.

You can also read about: Various Ways to Sort a Numpy array in Python

Leave a Reply

Your email address will not be published. Required fields are marked *