首页 > 解决方案 > 如何获得熊猫的滞后月平均值

问题描述

我有这样的数据: 其中 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 列中获得滞后的月平均值。

标签: pythonpandasnumpydata-science

解决方案


脚步:

  1. 首先转换data-type of the 日期。column to日期时间`。
  2. 分别提取year/month使用.dt.date /.dt.month
  3. 使用提取的值制作所需的组并使用函数聚合total_percentage_salemean以获得所需的输出
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

推荐阅读