Home > front end >  How do I aggregate datetime data by week using isocalendar in python?
How do I aggregate datetime data by week using isocalendar in python?

Time:12-02

I would like to aggregate datetime data to a weekly level. The following works with dt.week, but I receive a warning that dt.week has been deprecated. I have not had success with isocalendar yet. What would you recommend?

Here is an example of the data I would like to aggregate by week:

import pandas as pd
times = ['2021-01-28 08:00:00', '2021-01-26 08:00:00', '2021-01-25 08:00:00']
quantities = [40, 12, 43]
df = pd.DataFrame({'date':['2021-01-28 08:00:00','2021-01-26 08:00:00','2021-02-25 08:00:00'],
                   'quantity':[40, 12, 43]}) # 52 in one week, 43 in the other week
df['date'] = pd.to_datetime(df['date'])
df

The dt.week method works, but throws a warning:

df['week_num'] = df['date'].dt.week
df.groupby('week_num').sum('quantity')

Result: week_num 4 has a quantity of 52 and week_num 8 has a quantity of 43.

The warning reads <ipython-input-50-d66026a79596>:1: FutureWarning: Series.dt.weekofyear and Series.dt.week have been deprecated. Please use Series.dt.isocalendar().week instead. df['week_num'] = df['date'].dt.week

CodePudding user response:

I would just follow and try what it says:

>>> df.groupby(df['date'].dt.isocalendar().week).sum('quantity')
      quantity
week          
4           52
8           43

or, if you prefer week_num:

df.groupby(
    df['date'].dt.isocalendar().week
).sum('quantity').rename_axis(index='week_num')
  • Related