3

I am new to python and Pandas. I have a pandas data frame like the one below:

 id   value
  0    10
  1    0
  2    1
  3    3
  4    3
  5    3
  6    5

How can I get a list of bins and the number of items that fall into each bin. For example, in this case, I want something like this

 { {range: 0-1, count: 2}, 
   {range: 2-3, count: 3}, 
   {range: 4-5, count: 1}
 } 
Bahador Saket
  • 995
  • 1
  • 12
  • 24
  • Duplicate of https://stackoverflow.com/questions/16947336/binning-a-dataframe-in-pandas-in-python? – R2RT Jan 12 '18 at 16:40

1 Answers1

4

Use pd.cut, groupby, count, and to_dict:

df['range'] = pd.cut(df.value,[-1,2,4,6],labels=['0-1','2-3','4-5'])

df.groupby('range')['value'].count().reset_index(name='Count').to_dict(orient='records')

Output:

[{'range': '0-1', 'Count': 2}, {'range': '2-3', 'Count': 3}, {'range': '4-5', 'Count': 1}]
Scott Boston
  • 147,308
  • 15
  • 139
  • 187