# sciPy stats.binned_statistic() function | Python

stats.binned_statistic(x, values, statistic='mean', bins=10, range=None) function computes the binned statistics value for the given data (array elements).
It works similar to histogram function. As histogram function makes bins and counts the no. of points in each bin; this function computes the sum, mean, median, count or other statistics of the values for each bin.

Parameters :
arr : [array_like]input array to be binned.
values : [array_like]on which stats to be calculated.
statistics : Statistics to compute {mean, count, median, sum, function}. Default is mean.
bin : [int or scalars]If bins is an int, it defines the number of equal-width bins in the given range (10, by default). If bins is a sequence, it defines the bin edges.
range : (float, float) Lower and upper range of the bins and if not provided, range is from x.max() to x.min().

Results : Statistics value for each bin; bin edges; bin number.

Code #1 :

 # stats.binned_statistic() method  import numpy as np from scipy import stats     # 1D array arr = [20, 2, 7, 1, 34] print("\narr : \n", arr)        # median   print("\nbinned_statistic for median : \n", stats.binned_statistic(         arr, np.arange(5), statistic ='median', bins = 4))

Output :

arr :
[20, 2, 7, 1, 34]

binned_statistic for median :
BinnedStatisticResult(statistic=array([ 2., nan,  0.,  4.]),
bin_edges=array([ 1.,  9.25, 17.5, 25.75, 34.  ]),
binnumber=array([3, 1, 1, 1, 4], dtype=int64))

Code #2 :

 # stats.binned_statistic() method  import numpy as np from scipy import stats    # mean   arr = [20, 2, 7, 1, 34] print("\nbinned_statistic for mean : \n", stats.binned_statistic(         arr, np.arange(5), statistic ='mean', bins = 2))

Output :

binned_statistic for mean :
BinnedStatisticResult(statistic=array([2., 2.]),
bin_edges=array([ 1., 17.5, 34. ]),
binnumber=array([2, 1, 1, 1, 2], dtype=int64))

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.