0

I have a list of panda dataframe;

enter image description here

I would like to convert it into a panda dataframe that looks like this;

enter image description here

I tried something like panda_series.rolling(window=3).mean(). However, the problem is that the moving average is calculated starting from the last row. What I want is to have the moving average to be calculated starting from the first row.

FDL
  • 115
  • 8

2 Answers2

2

You can compute the rolling on the reversed Series, and set the min_periods to 1:

df['MA3'] = df['value'][::-1].rolling(window=3, min_periods=1).mean()

Output:

   value   MA3
0     12  13.0
1     13  14.0
2     14  14.5
3     15  15.0

Note that it is not necessary to reverse the output if you assign it back as a column due to the fact that pandas performs index alignement before inserting the data.

If you're working with an isolated Series, however, you will need to use:

s = df['value'][::-1].rolling(window=3, min_periods=1).mean()[::-1]

# or
# s2 = s1[::-1].rolling(window=3, min_periods=1).mean()[::-1]
mozway
  • 194,879
  • 13
  • 39
  • 75
  • your answer is almost perfect. To get the right order in the panda series as required in the question, the panda series in your answer needs to be reversed again. I wrote an answer to build on your answer. Do you mind editing your answer to make it perfect? – FDL Apr 15 '22 at 03:18
  • 1
    @FDL you only need to reverse it again if you work with the Series alone, if you assign it to a column, index alignement will do the job ;) I added this to the answer – mozway Apr 15 '22 at 03:35
  • 1
    As far as performance goes, there's an interesting answer about it [here](https://stackoverflow.com/a/65391420/11865956) – BeRT2me Apr 15 '22 at 03:49
0

I would like to build on the answer by @mozway. Credit goes to him.

To get the right order in the panda series as required in the question, here's the code.

df['MA3'] = df['value'][::-1].rolling(window=3, min_periods=1).mean()
df['MA3'] = df['MA3'][::-1]
FDL
  • 115
  • 8