Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of elements in a specific bin

I'm curious on whether its possible to count the number of elements for a specific bin in a histogram, i.e. all elements in ranges 0-10

how would you do this?

e.g. plt.hist(data, bins=[0, 10, 20, 30, 40, 50, 100]) would it be possible to count all elements from a dataset that go into bin 0-10

like image 589
souli Avatar asked Dec 08 '25 09:12

souli


2 Answers

Matplotlib histograms return the counts for each bin:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.uniform(0, 100, 1000)

counts, edges, plot = plt.hist(x, bins=[0, 10, 20, 50, 100])
print(counts)
print(counts[0]) # first bin
like image 55
MaxNoe Avatar answered Dec 10 '25 21:12

MaxNoe


Yes, pd.Series.value_counts has bins parameter.

import pandas as pd
s = pd.Series(np.random.randint(0,100,50))
s.value_counts(bins=[0,10,20,30,40,50,60,70,80,90,100]).sort_index()

Output:

(-0.001, 10.0]    8
(10.0, 20.0]      6
(20.0, 30.0]      5
(30.0, 40.0]      6
(40.0, 50.0]      2
(50.0, 60.0]      3
(60.0, 70.0]      4
(70.0, 80.0]      3
(80.0, 90.0]      6
(90.0, 100.0]     7
dtype: int64
like image 20
Scott Boston Avatar answered Dec 10 '25 23:12

Scott Boston