Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping data by multiple dates in pandas

Tags:

python

pandas

I have some data that has dates in it such as:

1979-02-15
1979-02-15
1979-02-17
1979-02-17

I would like to group the data both by year, month, and date so that the data looks like

1979
02
15

1979-02-15
1979-02-15

1979
02
17

1979-02-17
1979-02-17

I have found the function

grouped = df.groupby(lambda x: x.year)

but this only allows for grouping by the year. So, my question is how do I do multi-level grouping by date in pandas?

like image 788
user1074057 Avatar asked Mar 23 '26 21:03

user1074057


1 Answers

You can pass multiple keys to groupby as a list:

from pandas import *
from numpy.random import randn
rng = date_range('1/1/2011', periods=7200, freq='H')
ts = Series(randn(len(rng)), index=rng)
for key, data in ts.groupby([rng.year, rng.month]):
    print key, data.sum()
like image 182
HYRY Avatar answered Mar 26 '26 09:03

HYRY



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!