【问题标题】:how to aggregate data in Y axis and plot a line graph in python如何在Y轴上聚合数据并在python中绘制折线图
【发布时间】:2018-05-02 05:27:02
【问题描述】:

我有如下数据。我想在 python 中绘制一个简单的折线图,其中 X 轴上的项目和 Y 轴上的总销售额。总销售额是商品级别的总销售额。

有人可以帮忙吗?

Item    Date    Sales
Item1   4/25/2018   55
Item2   4/25/2018   21
Item3   4/25/2018   50
Item4   4/25/2018   58
Item5   4/25/2018   81
Item6   4/25/2018   79
Item7   4/25/2018   61
Item8   4/25/2018   37
Item9   4/25/2018   51
Item10  4/25/2018   53
Item1   4/26/2018   27
Item2   4/26/2018   28
Item3   4/26/2018   26
Item4   4/26/2018   95
Item5   4/26/2018   15
Item6   4/26/2018   89
Item7   4/26/2018   42
Item8   4/26/2018   21
Item9   4/26/2018   39
Item10  4/26/2018   67
Item1   4/27/2018   14
Item2   4/27/2018   45
Item3   4/27/2018   35
Item4   4/27/2018   68
Item5   4/27/2018   76
Item6   4/27/2018   63
Item7   4/27/2018   73
Item8   4/27/2018   61
Item9   4/27/2018   59
Item10  4/27/2018   93
Item1   4/28/2018   27
Item2   4/28/2018   63
Item3   4/28/2018   55
Item4   4/28/2018   73
Item5   4/28/2018   58
Item6   4/28/2018   90
Item7   4/28/2018   67
Item8   4/28/2018   72
Item9   4/28/2018   64
Item10  4/28/2018   98

问候, 菲利普

【问题讨论】:

  • 您应该考虑使用 pandas 来完成这项任务。日期与项目列。然后在另一列中每天汇总所有项目。然后绘制每一列与日期。如果这是一次性任务,使用 Excel/LibreOfficeCalc 会更快。

标签: python python-3.x matplotlib


【解决方案1】:

使用 pandas,可以通过将数据加载到数据框中、执行 groupby 并添加每个组的销售额值来实现。最终,pandas 封装了一些常用的 matplotlib 图,可以直接从 pandas 调用。

# df['Date'] = pd.to_datetime(df['Date']) # For the desired plot it is not necessary but
                                          # it is a good idea, and allow plots by date too 
df.groupby(by='Item').sum().plot.bar(y='Sales',color='g')

这会产生以下情节:

为了将项目从1到10按数字排序,可以在绘图前使用this answer

【讨论】:

    【解决方案2】:

    使用熊猫,

    import pandas as pd
    
    df = pd.read_csv('yourfile.csv')
    
    df_grp = df.groupby('Item')['Sales'].sum()
    df_grp = df_grp[df_grp.index.str.split('Item').str[1].astype(int).argsort()]
    df_grp.plot()
    plt.xticks(np.arange(df_grp.shape[0]), df_grp.index, rotation=90)
    

    输出:

    【讨论】:

      【解决方案3】:

      也可以选择不使用 pandas,仅使用 numpy。从包含项目列信息的数组items 和出售的sales 开始,代码如下所示:

      u, f = np.unique(items, return_inverse=True) # returns unique array of occurences and the indices to retrieve the original items array.
      # i.e. u, f = np.unique([1,2,3,1,1,2,1], return_inverse=True) returns
      # u: [1,2,3]
      # f: [0 1 2 0 0 1 0] such that u[f]==[1,2,3,1,1,2,1]
      imgs = np.bincount(f, sales) 
      inds = np.argsort(np.char.lstrip(u,'Item').astype(int))
      plt.plot(np.arange(len(u)),imgs[inds])
      plt.xticks(np.arange(len(u)),u[inds])
      

      注意:假设输入数组具有正确的 dtype,如果不是这种情况,则应使用 .astype() 将它们转换为正确的 dtype

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多