Skip to content
Advertisement

Get cumulative sum in pandas

Context

Datetime Campaign_name Status Open_time
2022-03-15 00:00 Funny_campaign Open
2022-03-15 01:00 Funny_campaign Continue
2022-03-15 02:00 Funny_campaign Continue
2022-03-15 03:00 Funny_campaign Continue
2022-03-15 04:00 Funny_campaign Close
2022-03-15 08:00 Funny_campaign Open
2022-03-15 09:00 Funny_campaign Continue
2022-03-15 10:00 Funny_campaign Close

Problem

I need to calculate the time from open to close.

My code right now

There are two approches I could go with. Get the open time in each ‘Close’ or a cumulative open_time in each ‘Open’ and ‘Continue’. Here is my take on the last one.

My code right now is almost fine, it doesn’t count the time between Close and Open but it forgets to sum the last time difference.

JavaScript

Advertisement

Answer

IIUC, you could start new groups on the opens and use:

JavaScript

Output:

JavaScript

Or to only assign to “Close”:

JavaScript

Output:

JavaScript

And for just the difference close-open for each group:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement