使用 pandas 中的两列计算平均值 [英] Calculate the mean value using two columns in pandas

查看:99
本文介绍了使用 pandas 中的两列计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a deal dataframe with three columns and I have sorted by the type and date, It looks like:

  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.我想得到这样的数据框:

There are many types (A, B, C,D,E…), I want to calculate the previous mean price of the same type of product. For example: the pre_mean_price value of third row A is (4+6)/2=5. I want to get a dataframe like this:

   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?非常感谢!

How can I calculate the pre_mean_price? Thanks a lot!

推荐答案

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

You can use expanding().mean() after groupby for each group , then shift the values.

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

这篇关于使用 pandas 中的两列计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆