Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Time Grouper: Custom Ranges

Tags:

python

pandas

Conditional on a datetime index, pd.TimeGrouper("AS") groups my data by calendar years. There is a variety of useful offsets shipped with pandas - but what if I want my own one?

For example, what if I'd like to group by 2-year periods, or 16 months? How would I approach that?

like image 658
FooBar Avatar asked Dec 29 '25 18:12

FooBar


1 Answers

Looks like that's in the next section on combining offsets, eg:

In [40]: rng = date_range('1/1/2015', periods=365, freq='D')
In [41]: d = Series(range(0, len(rng)), index=rng)

Group by month

In [42]: d.groupby(TimeGrouper('MS')).first()
Out[42]:
2015-01-01      1
2015-02-01     32
2015-03-01     60
2015-04-01     91
2015-05-01    121
2015-06-01    152
2015-07-01    182
2015-08-01    213
2015-09-01    244
2015-10-01    274
2015-11-01    305
2015-12-01    335
Freq: MS, dtype: int64

3 months:

In [43]: d.groupby(TimeGrouper('3MS')).first()
Out[43]:
2015-01-01      1
2015-04-01     91
2015-07-01    182
2015-10-01    274
Freq: 3MS, dtype: int64

So two years could be 2AS, 16 months could be 16MS

like image 116
jan zegan Avatar answered Dec 31 '25 07:12

jan zegan



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!