Skip to content
Advertisement

Cumulative count of column based on Month

I have a dataframe that looks like this:

JavaScript
Code Period
A 2022-04-29
A 2022-04-29
A 2022-04-30
A 2022-05-01
A 2022-05-01
A 2022-05-01

I have to create a new column, i.e., if the month ends then Count should start from 1.

Below is the code that I have tried at my end.

JavaScript
Code Period size
A 2022-04-29 2
A 2022-04-30 1
A 2022-05-01 3
JavaScript
Code Period size Count
A 2022-04-29 2 2
A 2022-04-30 1 3
A 2022-05-01 3 6

For the row with a Period of 2022-05-01, the total count should be 3 instead of 6 because a new month has started.

Advertisement

Answer

Use groupby on the month (and year to be safe) information from Period and apply cumsum:

JavaScript

Result:

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