【问题标题】:Groupby sum in years in pandas大熊猫中的分组总和
【发布时间】:2020-10-12 04:07:24
【问题描述】:

我有一个如下所示的数据框。这是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 轴 = 购买年份 Y轴=利润

【问题讨论】:

    标签: pandas matplotlib pandas-groupby


    【解决方案1】:

    使用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')
    

    【讨论】:

      猜你喜欢
      • 2017-02-06
      • 1970-01-01
      • 2021-02-23
      • 2020-09-04
      • 2020-02-21
      • 2018-10-07
      • 2019-05-20
      • 2018-07-30
      • 2018-03-07
      相关资源
      最近更新 更多