Monthly summation with pandas

I know there is a simple implementation for this, but I can’t remember the syntax. Have a simple pandas time series, and I want to summarize the data by month. In particular, I want to add data for several months and years to get some information about this. You can write it in slices, but I remember how the syntax does it automatically.

import pandas as pd df = Series(randn(100), index=pd.date_range('2012-01-01', periods=100)) 

A multi-indexed series over the years and months at the end of the month would be assigned as the first prize.

Partial Answer:

 ds.resample('M', how=sum) # for calendar monthly ds.resample('A', how=sum) # for calendar yearly 

Any idea how to get elegantly multi-indexed over years?

+4
source share
1 answer
 In [1]: import pandas as pd from numpy.random import randn In [2]: df = Series(randn(500), index=pd.date_range('2012-01-01', periods=500)) In [3]: s2 = df.groupby([lambda x: x.year, lambda x: x.month]).sum() In [4]: s2 Out[4]: 2012 1 3.853775 2 4.259941 3 4.629546 4 -10.812505 5 -16.383818 6 -5.255475 7 5.901344 8 13.375258 9 1.758670 10 6.570200 11 6.299812 12 7.237049 2013 1 -1.331835 2 3.399223 3 2.011031 4 7.905396 5 1.127362 dtype: float64 
+11
source

Source: https://habr.com/ru/post/1489509/


All Articles