简体   繁体   中英

Python DataFrame: Cumulative sum and subraction of multiple columns?

I have a df with name , marks and negative . I'm trying to do a cumulative sum and subract negative column.

    df

            name        marks       negative    

    0      marcus       20              0          
    1      marcus       30             10  
    2      marcus       0              20                 
    3      paul         10              0          
    4      bruno        50             50           
    5      bruno        20              0          
    6      lucy          0              5          





    Final df

            name        marks       negative    finsum

    0      marcus       20              0          20
    1      marcus       30             10          40           (20+30-10) - (finsum+marks-negative)
    2      marcus       0              20          20       
    3      paul         10              0          10
    4      bruno        50             50           0
    5      bruno        20              0          20
    6      lucy          0              5          -5

I have tried cumsum() for a single row, But how to add and subract with cumsum() or is there any other way?

Use GroupBy.cumsum :

df1 = df.groupby('name').cumsum()
df['fin'] = df1['marks'].sub(df1['negative'])

print (df)
     name  marks  negative  fin
0  marcus     20         0   20
1  marcus     30        10   40
2  marcus      0        20   20
3    paul     10         0   10
4   bruno     50        50    0
5   bruno     20         0   20
6    lucy      0         5   -5

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