Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas cumulative sum depending on other columns value

I have a Dataset like this

Date        Runner  Group   distance [km]
2021-01-01  Joe     1       7            
2021-01-02  Jack    1       6            
2021-01-03  Jess    1       9            
2021-01-01  Paul    2       11           
2021-01-02  Peter   2       12           
2021-01-02  Sara    3       15           
2021-01-03  Sarah   3       10           
 

and I want to calculate the cumulative sum for each group of runners.

Date        Runner  Group   distance [km]   cum sum [km]
2021-01-01  Joe     1       7               7
2021-01-02  Jack    1       6               13
2021-01-03  Jess    1       9               22
2021-01-01  Paul    2       11              11
2021-01-02  Peter   2       12              23
2021-01-02  Sara    3       15              15
2021-01-03  Sarah   3       10              25  

Unfortunately, I have no idea how to do this and I didn't find the answer somewhere else. Could someone give me a hint?

import pandas as pd
import numpy as np

df = pd.DataFrame([['2021-01-01','Joe', 1, 7],
                   ['2021-01-02',"Jack", 1, 6],
                   ['2021-01-03',"Jess", 1, 9],
                   ['2021-01-01',"Paul", 2, 11],
                   ['2021-01-02',"Peter", 2, 12],
                   ['2021-01-02',"Sara", 3, 15],
                   ['2021-01-03',"Sarah", 3, 10]],
                  columns=['Date','Runner', 'Group', 'distance [km]'])
like image 240
Peter Avatar asked Dec 05 '25 13:12

Peter


1 Answers

Try groupby cumsum:

>>> df['cum sum [km]'] = df.groupby('Group')['distance [km]'].cumsum()
>>> df
         Date Runner  Group  distance [km]  cum sum [km]
0  2021-01-01    Joe      1              7             7
1  2021-01-02   Jack      1              6            13
2  2021-01-03   Jess      1              9            22
3  2021-01-01   Paul      2             11            11
4  2021-01-02  Peter      2             12            23
5  2021-01-02   Sara      3             15            15
6  2021-01-03  Sarah      3             10            25
>>> 
like image 137
U12-Forward Avatar answered Dec 08 '25 02:12

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!