根据列表值对数据框列进行求和

时间:2017-11-24 22:16:59

标签: python pandas

我有一个数据帧df,头部看起来像:

             total_cost  
date                                                                       
2006-03-04 -1465.052092          
2006-04-04 -1213.508277     
2006-05-04 -1459.290503    
2006-06-04 -1460.119361     
2006-07-04  -772.482609

数据框具有多年来每天的值。

我有2个名单: yearList - 具有时间序列中的年份并且看起来像:

[2006,2007,2008,2009,2010,2011,2012]

monthList - 具有时间序列中涵盖的月份,如下所示:

[1,2,3,4,5,6,7,8,9,10,11,12]

我想(如果可能的话)创建一个数据框(按月份和年份编制索引),总结了total_cost列。

看起来像是:

year    month      cost
2006        1     12345
2006        2     12345
:                     :
2012       12     12345

上述输出数据框示例中的成本

我可以看到我可以使用(例如11月):

df['date'][df['date'].index.month == 11]

但是我如何添加year元素,所以伪代码看起来像2006年11月:

df['Dates'][df['Dates'].index.month == 11 && df['date'].index.year== 06]

1 个答案:

答案 0 :(得分:1)

IIUC。

df['Year']=df.index.year
df['Month']=df.index.month
df.groupby(['Year','Month'],as_index=False)['total_cost'].sum()
Out[319]: 
   Year  Month   total_cost
0  2006      3 -1465.052092
1  2006      4 -1213.508277
2  2006      5 -1459.290503
3  2006      6 -1460.119361
4  2006      7  -772.482609
相关问题