使用group by和sum

时间:2018-04-06 21:24:24

标签: python

我正在尝试使用以下数据绘制图表。我需要有图表年份与Txns

原始数据,即代码

中的dataset1 =
WeekDay Day Month   Year    Time    Txns
   1     5    1     2015      3       1
   1     5    1     2015      4       4
   1     5    1     2015      5       1
   1     5    1     2015      7       2

这是分组后的数据和sum,即代码中的plot =

Index       Txns
(2014, 12)  5786
(2015, 1)   70828
(2015, 2)   63228
(2015, 3)   74320

我的代码:

plot = dataset1.groupby(['Year', 'Month'])['Txns'].sum()
plot_df = plot.unstack('Month').loc[:, 'Txns']
plot_df.index = pd.PeriodIndex(plot_df.index.tolist(), freq='2015')
plot_df.plot()

我每次都会收到此错误:

  

KeyError:'标签[Txns]不在[栏]'

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

为什么不只是data.groupby('Year').Txns.sum()如果你想按年份分组并总和Txns

.plot()如果您想绘制它:

enter image description here

或年度行:

enter image description here