Python Pandas: Split a TimeSerie per month or week
The pd.TimeGrouper
is deprecated and will be removed, you can use pd.Grouper
instead.
weeks = [g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='W'))]
months = [g for n, g in df.groupby(pd.Grouper(key='timestamp',freq='M'))]
This way you can also avoid setting the timestamp
as index.
Also, if your timestamp is part of a multi index, you can refer to it using using the level
parameter (e.g. pd.Grouper(level='timestamp', freq='W')
). Than @jtromans for the heads up.
use groupby
with pd.TimeGrouper
and list comprehensions
weeks = [g for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('W'))]
months = [g for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('M'))]
You can reset the index if you need
weeks = [g.reset_index()
for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('W'))]
months = [g.reset_index()
for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('M'))]
in a dict
weeks = {n: g.reset_index()
for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('W'))}
months = {n: g.reset_index()
for n, g in df.set_index('timestamp').groupby(pd.TimeGrouper('M'))}