numpy.bincount() in Python (original) (raw)

Last Updated : 17 Nov, 2020

In an array of +ve integers, the numpy.bincount() method counts the occurrence of each element. Each bin value is the occurrence of its index. One can also set the bin size accordingly.
Syntax :

numpy.bincount(arr, weights = None, min_len = 0)

Parameters :

arr : [array_like, 1D]Input array, having positive numbers weights : [array_like, optional]same shape as that of arr min_len : Minimum number of bins we want in the output array

Return :

Output array with no. of occurrence of index value of bin in input - arr. Output array, by default is of the length max element of arr + 1. Here size of the output array would be max(input_arr)+1.

Code 1 : Working of bincount() in NumPy

Output :

Bincount output : [0 4 2 0 0 0 1] size of bin : 7

Bincount output : [0 1 3 0 1 5] size of bin : 6

Bincount output : [0 1 3 0 1 5 0 0 0 0] size of bin : 10

Code 2 : We can perform addition as per element with bincount() weight

import numpy as geek

array2 = [ 10 , 11 , 4 , 6 , 2 , 1 , 9 ]

array1 = [ 1 , 3 , 1 , 3 , 1 , 2 , 2 ]

bin = geek.bincount(array1, array2)

print ( "Summation element-wise : \n" , bin )

Output :

Summation element-wise : [ 0. 16. 10. 17.]

References :
https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html#numpy.bincount
.

Similar Reads