时间序列按周Python分组

时间:2018-12-18 12:52:41

标签: python pandas

我想按周在python中汇总此表:

    Date       x    y    z
   01/01/2016   0   0   1015
   02/01/2016   0   0   1015
   03/01/2016   0   0   1015
   04/01/2016   5   0   1020
   05/01/2016   6   1   1016
   06/01/2016   9   3   1020
   07/01/2016   4   0   1025
   08/01/2016   2   5   1008

谢谢。

1 个答案:

答案 0 :(得分:3)

首先通过reactstrap将列转换为日期时间,然后通过sumto_datetime进行汇总:

df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y')
print (df)
        Date  x  y     z
0 2016-01-01  0  0  1015
1 2016-01-02  0  0  1015
2 2016-01-03  0  0  1015
3 2016-01-04  5  0  1020
4 2016-01-05  6  1  1016
5 2016-01-06  9  3  1020
6 2016-01-07  4  0  1025
7 2016-01-08  2  5  1008

df1 = df.groupby(df['Date'].dt.weekofyear).sum()
print (df1)
       x  y     z
Date             
1     26  9  5089
53     0  0  3045

weekofyear

df2 = df.groupby(df['Date'].dt.dayofweek).sum()
print (df2)
      x  y     z
Date            
0     5  0  1020
1     6  1  1016
2     9  3  1020
3     4  0  1025
4     2  5  2023
5     0  0  1015
6     0  0  1015