-3

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

Jab
  • 26,853
  • 21
  • 75
  • 114

1 Answers1

0

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()
Riley
  • 2,153
  • 1
  • 6
  • 16