将数据集分布从每天转换为每周

问题描述

我有一个有关日常用餐记录的数据集,如下所示:

     Date          Meals           
   04-02-2020        2   
   05-02-2020        3  
   06-02-2020        2 
   07-02-2020        3
   08-02-2020        3
   09-02-2020        2 
   10-02-2020        1
   11-02-2020        3
   12-02-2020        3   
   13-02-2020        1  
   14-02-2020        2 
   15-02-2020        1
   16-02-2020        2
   17-02-2020        2 
   18-02-2020        3
 

我想将记录的分布从每天转换为每周,以便结果如下:

     Date (starting date of the week)         Meals (average no. Meals in each week)            
             04-02-2020                                  2   
             11-02-2020                                  2 

当我运行以下代码时:

df2=df.set_index('date')   # note that Date was datetime datatype
Output = df2.resample('W',loffset=pd.offsets.timedelta(days=-6)).apply({'Snack'  : 'mean'}) 

我收到此错误

---------------------------------------------------------------------------
SpecificationError                        Traceback (most recent call last)
<ipython-input-1382-5715acb0763f> in <module>
   ---->   1 Output = df2.resample('W',loffset=pd.offsets.timedelta(days=-6)).apply({'Snack' : 'mean'})        

~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/resample.py in aggregate(self,func,*args,**kwargs)
    279 
    280         self._set_binner()
--> 281         result,how = self._aggregate(func,**kwargs)
    282         if result is None:
    283             how = func

~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/base.py in _aggregate(self,arg,**kwargs)
    364                     obj.columns.intersection(keys)
    365                 ) != len(keys):
--> 366                     raise SpecificationError("nested renamer is not supported")
    367 
    368             from pandas.core.reshape.concat import concat

SpecificationError: nested renamer is not supported

有人可以帮忙吗? :(

谢谢 shosho

解决方法

df2 = (df
.set_index('date')
.groupby(pd.Grouper(freq='W')
.sum()
)