【问题标题】:Groupby by One column and get sum of values as columns based on monthsGroupby by One 列并根据月份将值的总和作为列获取
【发布时间】:2018-12-04 19:33:37
【问题描述】:

我有一个 pandas 数据框,其中包含在某个日期带来的项目及其数量。例如。

date         Item     qty
2016-01-04    Rice     3
2016-01-04    Ball     3
2016-01-10    Rice     5
2016-02-02    Coffee  10
2016-02-06    Rice     3
 .....         ...    ..

数据为 2 年,2016 年至 2018 年 5 月。

我想知道从 2016 年 1 月到 2018 年 5 月,每个月每件商品的销售量。并为其绘制折线图(x 轴 - 月,y - 产品数量)

为此,我想到了以这种格式创建一个数据框:

Date    Rice   Coffee   Ball
Jan 16   8       0       3
Feb 16   10      17      5
 ....    ...    ...      ...
May 18   11      9       12

我怎样才能得到这种格式的数据??

我认为的一个选项是 df.groupby([df.date.dt.year.rename('year'),df.date.dt.month.rename('month')]).agg({'qty':np.sum}).reset_index()

但它不起作用,有没有更好的方法来获取上述格式的结果,或者有更好的方法来存储结果以便绘制?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我想你想要这样,

    df= df.groupby([(df.index.year),(df.index.month),'Item']).sum().unstack(fill_value=0)
    df.columns=df.columns.droplevel()
    df.plot(kind='bar')
    plt.show()
    

    O/P

    【讨论】:

      【解决方案2】:

      给定

      >>> df
              date    Item  qty
      0 2016-01-04    Rice    3
      1 2016-01-04    Ball    3
      2 2016-01-10    Rice    5
      3 2016-02-02  Coffee   10
      4 2016-02-06    Rice    3
      

      >>> df.dtypes
      date    datetime64[ns]
      Item            object
      qty              int64
      dtype: object
      

      你可以的

      >>> from pandas.tseries.offsets import MonthEnd
      >>> offset = MonthEnd()
      >>> 
      >>> df.set_index('date').groupby([offset.rollforward, 'Item']).sum().unstack(fill_value=0)
                  qty            
      Item       Ball Coffee Rice
      2016-01-31    3      0    8
      2016-02-29    0     10    3
      

      我会保留这样的索引,因为那里有可用的日期。如果您确实必须将这些转换为'Jan 16' 之类的字符串,您可以这样做:

      >>> result = df.set_index('date').groupby([offset.rollforward, 'Item']).sum().unstack(fill_value=0)
      >>> result.index = result.index.map(lambda d: d.strftime('%b %y'))
      >>> result
              qty            
      Item   Ball Coffee Rice
      Jan 16    3      0    8
      Feb 16    0     10    3
      

      【讨论】:

        【解决方案3】:

        Series.dt.strftime 用于自定义format of datetimes 并聚合sum

        df = df.groupby([df.date.dt.strftime('%b %y'), 'Item'])['qty'].sum().unstack(fill_value=0)
        

        如果日期时间的顺序很重要,请使用ordered categoricals:

        df = df.sort_values('date')
        dates = df.date.dt.strftime('%b %y')
        dates = pd.Categorical(dates, ordered=True, categories=dates.unique())
        df1 = df.groupby([dates, 'Item'])['qty'].sum().unstack(fill_value=0)
        

        reindex:

        df = df.sort_values('date')
        dates = df.date.dt.strftime('%b %y')
        df1 = df.groupby([dates, 'Item'])['qty'].sum().unstack(fill_value=0).reindex(dates.unique())
        

        print (df1)
        Item    Ball  Coffee  Rice
        Jan 16     3       0     8
        Feb 16     0      10     3
        

        DataFrame.plot.bar的最后一张图:

        df1.plot.bar()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-31
          • 1970-01-01
          • 2013-05-11
          • 2021-01-18
          • 2017-08-20
          • 2018-01-19
          • 1970-01-01
          • 2021-08-10
          相关资源
          最近更新 更多