简体   繁体   中英

comparing the last values of groupby in each group - pandas

This is my dataframe:

df = pd.DataFrame({'a':[100, 105, 110, 150, 160], 'b':[2,2,1,3,2], 'c':[200, 210, 110, 450, 300], 'x':[0,0,0,1,1]})

    a  b    c  x
0  100  2  200  0
1  105  2  210  0
2  110  1  110  0
3  150  3  450  1
4  160  2  300  1

I add this column next:

df['csum'] = df.groupby('x')['c'].cumsum()

I want to add another column that shows the difference (in percentage) between the last csum of 0 (which is 520) and the last csum of 1 (which is 750). In this case the difference is 44.23 percent. My desired outcome looks like this:

     a  b    c  x  csum   result
0  100  2  200  0   200    44.23
1  105  2  210  0   410    44.23
2  110  1  110  0   520    44.23
3  150  3  450  1   450    44.23
4  160  2  300  1   750    44.23

Check with last

df['result']=df.groupby('x').csum.last().pct_change().iloc[-1]
df
Out[891]: 
     a  b    c  x  csum    result
0  100  2  200  0   200  0.442308
1  105  2  210  0   410  0.442308
2  110  1  110  0   520  0.442308
3  150  3  450  1   450  0.442308
4  160  2  300  1   750  0.442308

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM