Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas aggregate based on continuous same rows

Suppose I have this data frame and I want to aggregate and sum values on column 'a' based on the labels that have the same amount.

    a  label
0   1    0
1   3    0
2   5    0
3   2    1
4   2    1
5   2    1
6   3    0
7   3    0
8   4    1

The desired result will be:

    a  label
0   9    0
1   6    1
2   6    0
3   4    1

and not this:

    a  label
0   15    0
1   10    1
like image 845
Anita Avatar asked Jul 09 '26 02:07

Anita


1 Answers

IIUC

s=df.groupby(df.label.diff().ne(0).cumsum()).agg({'a':'sum','label':'first'})
s
Out[280]: 
       a  label
label          
1      9      0
2      6      1
3      6      0
4      4      1
like image 186
BENY Avatar answered Jul 10 '26 16:07

BENY