英文:
How to get the monthly average of a sales
问题
你好,Stackoverflow社区,
我正在尝试计算每月销售额的平均值。我知道要获取截止到当前月的销售额,我可以筛选特定日期范围,但如何计算每月销售额的平均值或任何特定的整数类型呢?底部的代码是我用来计算每月平均值的代码,但它只显示了每月的平均销售额。
df.groupby(pd.PeriodIndex(df['Date'], freq="M"))['sales'].mean()
我想要做的是找出他们每月平均销售额是多少。请有人帮助我解决这个问题吗?
英文:
Hello Stackoverflow Community,
I am struggling to try and get the monthly average of sales. I know that in order for me to get the current month to date I could just filter for a specific date range but how would someone go about getting the monthly average of sales or any specific integer type. The code on the bottom is the code that I used to find the monthly average but it just showed me the average amount of sales that were made each month.
df.groupby(pd.PeriodIndex(df['Date'], freq="M"))['sales'].mean()
What I am trying to do is find out what is the average amount of sales that they make on a monthly bases. Could someone please help me figure this out?
答案1
得分: 0
以上命令将返回每个月的平均销售额。
然而,看起来您只是寻找所有月份的平均销售额。
在这方面,只需将上述命令产生的数据转换为数组,然后使用numpy计算平均值。
举个例子,假设存在一个包含记录温度的日期数组。
以下是给定月份的平均温度:
>>> data=df.groupby(pd.PeriodIndex(df['date'], freq="M"))['temp'].mean()
>>> data
date
2019-10 2.000000
2019-11 5.000000
2020-01 3.025000
...
2023-06 23.552381
2023-07 16.975000
Freq: M, Name: temp, dtype: float64
然而,计算这些月份的总体平均值可以按如下方式进行:
>>> data=np.array(data)
>>> data
array([ 2. , 5. , 3.025 , 5.5625 , 2.7 ,
19.30652174, 19.4 , 25.42857143, 10.7 , 11.68235294,
...
2.13551402, 5.55135135, 8.48095238, 8.49677419, 12.48571429,
23.55 , 23.55238095, 16.975 ])
>>> np.mean(data)
13.508786668026012
这个例子中的平均值13.5代表了所有月份的平均值。
英文:
The above command will return the average sales made for each month.
However, it appears that you are simply looking for the average sales across all months.
In this regard, it is simply a matter of converting the data yielded from the above command into an array and then calculate the average using numpy.
To use another example, suppose there exists an array of dates with recorded temperatures.
The following yields the average temperature in a given month:
>>> data=df.groupby(pd.PeriodIndex(df['date'], freq="M"))['temp'].mean()
>>> data
date
2019-10 2.000000
2019-11 5.000000
2020-01 3.025000
...
2023-06 23.552381
2023-07 16.975000
Freq: M, Name: temp, dtype: float64
However, calculating the overall average across these months can be performed as follows:
>>> data=np.array(data)
>>> data
array([ 2. , 5. , 3.025 , 5.5625 , 2.7 ,
19.30652174, 19.4 , 25.42857143, 10.7 , 11.68235294,
...
2.13551402, 5.55135135, 8.48095238, 8.49677419, 12.48571429,
23.55 , 23.55238095, 16.975 ])
>>> np.mean(data)
13.508786668026012
The mean value of 13.5 in this example represents the average calculated across all months.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论