Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you in advance!

>Solution :

df['cumulative_PnL'] = df.groupby('account')['PnL'].cumsum()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading