【问题标题】:Analyse monthly sale in python用python分析每月销售额
【发布时间】:2020-01-27 14:38:00
【问题描述】:

我有一个这样的数据集

  order_status  created_at
0    cancelled  05/08/2018
1    cancelled  06/08/2018
2   dispatched  27/08/2018
3   dispatched  30/08/2018
4    cancelled  05/09/2018
5   dispatched  05/09/2018
6   dispatched  25/09/2018
7    cancelled  23/10/2018
8   dispatched  05/10/2018
9   dispatched  02/08/2018

日期格式为 dd/mm/yy。我想要的是按月分析数据,比如今年第 8 个月取消了多少订单,今年第 9 个月发货了多少。我正在做的是这样的

df2 = df[['order_status','created_at']].\
         set_index('created_at').\
         resample('M')
df2.iplot(kind='bar', xTitle='Date', yTitle='Order Status',
    title='Monthly Order Status')

但它会抛出错误

TypeError:仅适用于 DatetimeIndex、TimedeltaIndex 或 PeriodIndex,但得到了一个“索引”实例

如何获取所有订单的月度报告?

【问题讨论】:

  • 你需要一个聚合函数在resample之后,例如...resample('M').sum()。不过,您需要先透视这些数据
  • 是的,但我使用分类值(已取消、已调度)进行分析
  • 是的,您应该首先pivot,将跨列的状态和日期作为行索引。尝试使用pandas.crosstab- 所以把它们放在一起,试试pd.crosstab(df['created_at'], df['order_status']).resample('M').sum().plot(kind='bar')

标签: python pandas matplotlib seaborn


【解决方案1】:

您可以使用groupby

df['created_at'] = pd.to_datetime(df['created_at'])    
f = df.groupby(df.created_at.dt.month)['order_status'].value_counts().reset_index(name='count')

      created_at order_status  count
0           2   dispatched      1
1           5    cancelled      2
2           5   dispatched      2
3           6    cancelled      1
4           8   dispatched      2
5           9   dispatched      1
6          10    cancelled      1

# plot
f.plot(kind='bar')

【讨论】:

  • 您好,感谢您的回复,我该如何绘制这些数据?
【解决方案2】:

您可以使用pandas.datetime 方法从日期获取月份。

df['month'] = df['created_at'].map(lambda x: x.month)

之后,通过value_counts,你可以通过这种方式统计有多少订单被取消或派送:

df[df['dispatched']=='cancelled']['month'].value_counts()

希望对你有帮助。

注意

如果您的日期中有不同的年份,您可以使用一些数学运算来获得年份和月份的信息:

df['year_month'] = df['created_at'].map(lambda x: 100*x.year + x.month)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多