How to group by bins in Pandas?

Viewed 24

All other questions on this topic are too complex. I think I'm missing something, do I need to use Pandas aggregate function?

Input:

df_dict = pd.DataFrame({'Position': {149: 1.0,
  95: 1.0,
  1031: 1.0,
  880: 1.0,
  868: 1.1,
  862: 1.1111111111111112,
  886: 1.2,
  908: 1.3888888888888888,
  874: 1.4193548387096775,
  920: 1.5},
 'Ctr': {149: 0.0,
  95: 0.0,
  1031: 0.0,
  880: 0.4,
  868: 0.5,
  862: 0.3333333333333333,
  886: 0.4,
  908: 0.3888888888888889,
  874: 0.2580645161290322,
  920: 0.5}})

df_dict

enter image description here

Output:

Position    Ctr

1-10        sum
11-20       sum 
1 Answers

Use cut with aggregate sum:

bins = [0,10,20]
labels = [f'{i+1}-{j}' for i, j in zip(bins[:-1], bins[1:])] 

s = pd.cut(df_dict['Position'], bins = bins, labels = labels)
df = df_dict.groupby(s)['Ctr'].sum().reset_index()
print (df)
  Position       Ctr
0     1-10  2.780287
1    11-20  0.000000
Related