【问题标题】:Calculate the average share of sales for each day of the week计算一周中每一天的平均销售额份额
【发布时间】:2020-09-09 21:43:35
【问题描述】:

我有一个销售时间序列数据框,我需要计算一周中每一天的平均销售份额。下面是我想要的一个例子:

  • df1:销售时间序列数据框。
  • share_sales_week_of_day - 想要 DataFrame。对于星期一,我计算了实际价值。这里2842 = 来自数据框的每周总销售额,18 = 星期一的销售额。

代码:

df1 = pd.DataFrame(index = ['2011-01-31', '2011-02-01', '2011-02-01', '2011-02-02', '2011-02-03', '2011-02-04', '2011-02-05', '2011-02-06', '2011-02-07', '2011-02-08', '2011-02-09', '2011-02-10', '2011-02-11', '2011-02-12'], 
                   data = [1,2,3,4,5,6,7,  8,8,8,3,4,5,6], columns = ['sales'])

share_sales_week_of_day = pd.DataFrame(data = {'d_1' : [0.5*(1.0/28 + 8.0/42)],'d_2' : [0], 'd_3' : [0], 'd_4' : [0], 'd_5' : [0], 'd_6' : [0], 'd_7' : [0]})

你能解释一下我如何计算整个数据的份额....

【问题讨论】:

  • 1) 在您计算出星期几是什么日期(“星期一”、“星期二”等)之前,您需要首先将日期从 strings(如 '2011-01-31')转换为实际的 datetimes。 pandas 中有什么功能可以做到这一点?当您阅读 pandas 文档时,它告诉您什么?
  • 2) 然后,将索引转换为日期时间后,请参阅Get weekday/day-of-week for Datetime column of DataFrame
  • 3) 然后,哪个 pandas 函数会将 date,sales 条目的(“长格式”)数据帧转换为 table 其中 day -of-week 在中,条目是每天sales 值的总和(聚合)?同样,pandas 文档告诉你什么?

标签: python pandas dataframe


【解决方案1】:

让我们做pd.crosstab

df.index=pd.to_datetime(df.index) 

s=pd.crosstab(index=df1.index.strftime('%U'),columns=df1.index.weekday,values=df1.sales.values,aggfunc='sum',normalize='index').mean()
col_0
0    0.113095
1    0.184524
2    0.107143
3    0.136905
4    0.166667
5    0.196429
6    0.095238
dtype: float64

s.to_frame().T
col_0         0         1         2         3         4         5         6
0      0.113095  0.184524  0.107143  0.136905  0.166667  0.196429  0.095238

【讨论】:

  • 这会抛出错误AttributeError: 'Index' object has no attribute 'strftime'
  • @ChihebNexus df.index=pd.to_datetime(df.index)
  • 是的,但您必须将此添加到您的答案中,以防我们点击AttributeError
  • 一周内增加的销售复杂度可以为零
猜你喜欢
  • 2016-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多