Search code examples
pythonpandasdataframecumulative-sum

Python: cumulative sum of column based on unique values


I have a DataFrame with columns as follows

df:
            account  PnL  
date
2022-01-01        1  100  
2022-01-01        2   30  
2022-01-02        1   -5   
2022-01-02        2   10
2022-01-03        1   10   
2022-01-03        2    5

I want to get a DataFrame with a column containing the cumulative sum of the PnL, based on account. So the result should look like this:

df:
            account  PnL  cumulative_PnL 
date
2022-01-01        1  100  100
2022-01-01        2   30   30
2022-01-02        1   -5   95
2022-01-02        2   10   40
2022-01-03        1   10  105
2022-01-03        2    5   45 

Is there a pythonic way to do this without getting into for loops?

Thank you in advance!


Solution

  • df['cumulative_PnL'] = df.groupby('account')['PnL'].cumsum()