cumulative month to date and year to date sum

Viewed 31

I am having issues finding a solution for the cummulative sum for mtd and ytd

I need help to get this result

Final result

1 Answers

Use groupby.cumsum combined with periods using to_period:

# ensure datetime
s = pd.to_datetime(df['date'], dayfirst=False)
# group by year
df['ytd'] = df.groupby(s.dt.to_period('Y'))['count'].cumsum()
# group by month
df['mtd'] = df.groupby(s.dt.to_period('M'))['count'].cumsum()

Example (with dummy data):

         date  count  ytd  mtd
0  2022-08-26      6    6    6
1  2022-08-27      1    7    7
2  2022-08-28      4   11   11
3  2022-08-29      4   15   15
4  2022-08-30      8   23   23
5  2022-08-31      4   27   27
6  2022-09-01      6   33    6
7  2022-09-02      3   36    9
8  2022-09-03      5   41   14
9  2022-09-04      8   49   22
10 2022-09-05      7   56   29
11 2022-09-06      9   65   38
12 2022-09-07      9   74   47
Related