Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Start Week on Sunday when Using Group By for Dates and counting events in the period

I have some data and a date column. By running the command below, it goes through the DF and counts all the events happened during that week.

df['date'].groupby(df.date.dt.to_period("W")).agg('count')

The result is something like:

2018-04-16/2018-04-22    40
2018-04-23/2018-04-29    18

The weeks starts on Monday and end Sunday.

I want the week to start on Sunday and end on Saturday. So, the data should be

2018-04-15/2018-04-21    40
2018-04-22/2018-04-28    18 
like image 884
Imsa Avatar asked Dec 21 '25 09:12

Imsa


1 Answers

Use:

df = pd.DataFrame({'Date':np.random.choice(pd.date_range('2018-04-10',periods=365, freq='D'),1000)})

df.groupby(df['Date'].dt.to_period('W-SAT')).agg('count')

Output:

                       Date
Date                       
2018-04-08/2018-04-14    12
2018-04-15/2018-04-21    19
2018-04-22/2018-04-28    21
2018-04-29/2018-05-05    16
2018-05-06/2018-05-12    21
like image 116
Scott Boston Avatar answered Dec 23 '25 23:12

Scott Boston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!