【问题标题】:Calculate the mean value using two columns in pandas使用熊猫中的两列计算平均值
【发布时间】:2021-02-27 10:06:39
【问题描述】:

我有一个包含三列的交易数据框,我已按类型和日期排序,它看起来像:

  type    date      price
   A    2020-05-01   4
   A    2020-06-04   6
   A    2020-06-08   8
   A    2020-07-03   5
   B    2020-02-01   3
   B    2020-04-02   4

种类很多(A、B、C、D、E……),我要计算同类型产品之前的平均价格。例如:第三行A的pre_mean_price值为(4+6)/2=5。我想得到这样的数据框:

   type    date      price  pre_mean_price
   A    2020-05-01   4       .
   A    2020-06-04   6       4
   A    2020-06-08   8       5 
   A    2020-07-03   5       6
   B    2020-02-01   3       .
   B    2020-04-02   4       3

如何计算 pre_mean_price?非常感谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以在 groupby 之后为每个组使用 expanding().mean() ,然后移动值。

    df['pre_mean_price'] = df.groupby("type")['price'].apply(lambda x: 
                                                             x.expanding().mean().shift())
    print(df)
    

      type        date  price  pre_mean_price
    0    A  2020-05-01      4             NaN
    1    A  2020-06-04      6             4.0
    2    A  2020-06-08      8             5.0
    3    A  2020-07-03      5             6.0
    4    B  2020-02-01      3             NaN
    5    B  2020-04-02      4             3.0
    

    【讨论】:

      【解决方案2】:

      类似

      df['pre_mean_price'] = df.groupby('type').expanding().mean().groupby('type').shift(1)['price'].values
      

      产生

        type        date  price  pre_mean_price
      0    A  2020-05-01      4             NaN
      1    A  2020-06-04      6             4.0
      2    A  2020-06-08      8             5.0
      3    A  2020-07-03      5             6.0
      4    B  2020-02-01      3             NaN
      5    B  2020-04-02      4             3.0
      

      简短说明

      这个想法是

      • 第一组由"type".groupby()。必须这样做,因为我们要计算组“类型”的(增量)均值。
      • 然后,使用expanding().mean() 计算增量平均值。此时的输出是
              price
      type
      A    0   4.00
           1   5.00
           2   6.00
           3   5.75
      B    4   3.00
           5   3.50
      
      • 然后,再次按"type" 进行分组,并使用shift(1) 将组内的元素移动一行。
      • 然后,只需提取price 列的值(增量方式)
      • 注意:假设您的数据按日期排序。不是,请先拨打df.sort_values('date', inplace=True)

      【讨论】:

        猜你喜欢
        • 2022-11-14
        • 2020-03-03
        • 2019-12-23
        • 1970-01-01
        • 1970-01-01
        • 2020-04-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多