[英]Compute moving average in pandas with a twist
This seems very simple to achieve in excel.这在excel中似乎很容易实现。 Not sure how to do this with pandas.
不知道如何用熊猫做到这一点。
My data set looks as follows我的数据集如下所示
[Row,Flag,Value
1,FALSE,3
2,FALSE,1
3,FALSE,2
4,FALSE,3
5,FALSE,5
6,TRUE,nan
7,TRUE,nan
8,TRUE,nan
9,TRUE,nan]
I wan an output that looks like我想要一个看起来像的输出
[Row,Flag,Value
1,FALSE,3
2,FALSE,1
3,FALSE,2
4,FALSE,3
5,FALSE,5
6,TRUE,2.75
7,TRUE,3.19
8,TRUE,3.48
9,TRUE,3.61]
I want an output that computes moving average of previous 4 rows when flag = TRUE.我想要一个输出,当标志 = TRUE 时计算前 4 行的移动平均值。 Additionally, the calculation should use the recently computed average when it moves to next row.
此外,计算应在移动到下一行时使用最近计算的平均值。 From the above example, its obvious that the average for row 6 is
(5+3+3+1)/4 = 2.75
.从上面的例子中,很明显,第 6 行的平均值是
(5+3+3+1)/4 = 2.75
。 The average of row 7 should include the recently compute Row 6 value (**2.75**,5,3,2)/4 = 3.19
第 7 行的平均值应包括最近计算的第 6 行值
(**2.75**,5,3,2)/4 = 3.19
I've referred to the following article but that dint help much Pandas - moving averages - use values of previous X entries for current row我已经参考了以下文章,但这对Pandas - 移动平均 - 使用当前行的前 X 个条目的值有很大帮助
Just use a for loop只需使用 for 循环
for i in range(len(df)):
if df["Flag"].iloc[i]:
df["Value"].iloc[i] = df.loc[:,"Value"].iloc[i-4:i].mean()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.