【问题标题】:How to obtain the lagged monthly average value in pandas如何获得熊猫的滞后月平均值
【发布时间】:2021-08-16 11:58:21
【问题描述】:

我有这样的数据:其中 total_percentage_sale 是该时间段内产品的销售百分比。

date.       product      sale   total_percentage_sale
2019-01-01.  productA.   12.    30
2019-01-01.  productB.   10.    25
2019-02-01.  productC.   8.     20
2019-02-01.  productD.   10.    25   

我想从 total_percentage_sale 列中获取滞后的月平均值。

【问题讨论】:

  • 您的意思是对于特定的year/month grouptotal_percentage_saleaverage 是什么?
  • 特定月份。总销售百分比的平均值为 25,但 1 月的平均值为 27.5,2 月的平均值为 22.5

标签: python pandas numpy data-science


【解决方案1】:

步骤:

  1. 首先转换data-type of the date.column todatetime`。
  2. 分别使用.dt.date /.dt.month提取year/month
  3. 使用提取的值制作所需的组,并将total_percentage_sale 列与mean 函数聚合以获得所需的输出
df['date.'] = pd.to_datetime(df['date.'].str.strip('.'))
df.groupby([df['date.'].dt.year.values , df['date.'].dt.month.values]).agg({'total_percentage_sale' : 'mean'})

输出:

            total_percentage_sale
2019    1   27.5
        2   22.5

【讨论】:

    【解决方案2】:

    试试这个更简单的方法,它返回所需列的月平均值 -

    df.groupby(['date'], sort=True)['total_percentage_sale'].mean()
    

    【讨论】:

      猜你喜欢
      • 2023-02-17
      • 1970-01-01
      • 2015-09-11
      • 2021-04-04
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 2015-07-18
      相关资源
      最近更新 更多