2016-11-11 691 views
2

我已经将我的数据加载到Pandas数据框中。Python,将数据框中的每日数据汇总为每月和每季度

实施例:

Date  Price 
2012/12/02 141.25 
2012/12/05 132.64 
2012/12/06 132.11 
2012/12/21 141.64              
2012/12/25 143.19 
2012/12/31 139.66 
2013/01/05 145.11 
2013/01/06 145.99 
2013/01/07 145.97 
2013/01/11 145.11 
2013/01/12 145.99 
2013/01/24 145.97 
2013/02/23 145.11 
2013/03/24 145.99 
2013/03/28 145.97 
2013/04/28 145.97 
2013/05/24 145.97 
2013/06/23 145.11 
2013/07/24 145.99 
2013/08/28 145.97 
2013/09/28 145.97 

仅有两列,一个是数据和一个是价格。

现在如何对数据进行分组或重新采样从2013年开始到每月和每季度的df?

每月:

Date  Price 
2013/01/01 Monthly total 
2013/02/01 Monthly total 
2013/03/01 Monthly total 
2013/04/01 Monthly total 
2013/05/01 Monthly total 
2013/06/01 Monthly total 
2013/07/01 Monthly total 
2013/08/01 Monthly total 
2013/09/01 Monthly total 

季刊:

Date  Price 
2013/01/01 Quarterly total 
2013/04/01 Quarterly total 
2013/07/01 Quarterly total 

请注意,月度和季度数据需要的月数据从一个月的第一天,但​​在原来的数据帧的第一天开始缺失,每个月有效每日数据的数量可能会有所不同。另外,原来的数据帧中有数据2012至2013年,我只能从2013年

开始需要月度和季度数据我想是这样

result1 = df.groupby([lambda x: x.year, lambda x: x.month], axis=1).sum() 

,但不起作用。

谢谢!

回答

6

首先转换您的日期列到日期时间指数:

df.Date = pd.to_datetime(df.Date) 
df.set_index('Date', inplace=True) 

然后使用resample。偏移量别名列表位于pandas documentation中。对于月份重新采样的开始,请使用MSQS作为季度:

df.resample('QS').sum() 
Out[46]: 
       Price 
Date    
2012-10-01 830.49 
2013-01-01 1311.21 
2013-04-01 437.05 
2013-07-01 437.93 

df.resample('MS').sum() 
Out[47]: 
      Price 
Date    
2012-12-01 830.49 
2013-01-01 874.14 
2013-02-01 145.11 
2013-03-01 291.96 
2013-04-01 145.97 
2013-05-01 145.97 
2013-06-01 145.11 
2013-07-01 145.99 
2013-08-01 145.97 
2013-09-01 145.97 
+0

太棒了!我在groupby函数,lambda表达式上挣扎了2天......非常感谢! – Windtalker

+0

因此,如果我有重复的日期,那么df.set_index仍然有效?或者我需要先处理重复的数据数据? – Windtalker

+0

无关紧要,试试看,改变样品中的日期以获得一个愚蠢,你会看到一切都会按预期工作。 – Boud

相关问题