Python 如何获取大熊猫的滞后月平均值

Python 如何获取大熊猫的滞后月平均值,python,pandas,numpy,data-science,Python,Pandas,Numpy,Data Science,我有这样一个数据: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是一个产品在一段时间内的销售百分比

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   

我想从销售总额百分比栏中获得滞后月平均值。

步骤:

  • 首先将date.
    列的
    数据类型转换为
    datetime`
  • 分别使用
    .dt.date/.dt.month
    提取
    年/月
  • 使用提取的值进行所需的分组,并使用
    mean
    函数聚合
    total\u percentage\u sale
    列以获得所需的输出
  • 输出:

                total_percentage_sale
    2019    1   27.5
            2   22.5
    

    尝试这个简单得多的方法,返回所需列的月平均值-

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

    您的意思是对于特定的
    年/月组
    特定月份的
    总销售额百分比
    平均值是多少。总销售额的平均百分比为25,但1月份的平均百分比为27.5,2月份的平均百分比为22.5
    
    df.groupby(['date'], sort=True)['total_percentage_sale'].mean()