以熊猫为单位的按年汇总

时间:2020-06-22 10:09:02

标签: pandas matplotlib pandas-groupby

我有一个数据框,如下所示。这是两种保健产品从2016年12月到2018年11月的销售数据。

product     profit      sale_date      discount
   A         50         2016-12-01      5
   A         50         2017-01-03      4
   B         200        2016-12-24      10
   A         50         2017-01-18      3
   B         200        2017-01-28      15
   A         50         2017-01-18      6
   B         200        2017-01-28      20
   A         50         2017-04-18      6
   B         200        2017-12-08      25
   A         50         2017-11-18      6
   B         200        2017-08-21      20
   B         200        2017-12-28      30
   A         50         2018-03-18      10
   B         300        2018-06-08      45
   B         300        2018-09-20      50
   A         50         2018-11-18      8
   B         300        2018-11-28      35

从上面我想在数据框下面准备并将其绘制成线图。

预期产量

bought_year          total_profit
2016                 250
2017                 1250
2018                 1000

X轴= buy_year Y轴=利润

1 个答案:

答案 0 :(得分:2)

使用groupbydt.year.agg来命名您的列。

df1 = df.groupby(df['sale_date'].dt.year).agg(total_profit=('profit','sum'))\
                            .reset_index().rename(columns={'sale_date': 'bought_year'})


print(df1)

   bought_year  total_profit
0         2016           250
1         2017          1250
2         2018          1000

df1.set_index('bought_year').plot(kind='bar')

enter image description here