简体   繁体   中英

Compute moving average in pandas with a twist

This seems very simple to achieve in 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. 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 . The average of row 7 should include the recently compute Row 6 value (**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

Just use a for loop

for i in range(len(df)):
    if df["Flag"].iloc[i]:
        df["Value"].iloc[i] = df.loc[:,"Value"].iloc[i-4:i].mean()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM