Jayn Jayn - 5 months ago 11
Python Question

How to make statistic according to week unit in pandas?

I have a DataFrame like this:


usr1 usr2
2016-01-01 20 NaN
2016-01-02 13 12
2016-01-03 NaN 12
2016-01-04 NaN 23
2016-01-05 13 21
2016-01-06 20 NaN
2016-01-07 NaN 12
2016-01-08 NaN 23
2016-01-09 13 21
2016-01-10 20 NaN
. . .
. . .

the index is the date, and what I want to do is trying to get the sum of every week(period is 7 days,from Monday to Sunday),and the result will be like this:


usr1 usr2
week1 33 24
week2 13 12
week3 66 100
. . .
. . .

How can I achieve this goal?

Answer

You can use .resample():

df.resample('W').sum()

If you don't want to keep the date_time values that indicate when the weeks occurred, you can .reset_index(drop=True).