1

Let's say we have a dataframe like this:

Time = ['00:01', '00:02','00:03','00:04','00:05','00:06','00:07','00:08','00:09']
Value = [2.5, 3.2, 4.6, 3.6, 1.5, 2.5, 0.4, 5.7, 1.5]   
df = pd.DataFrame({'Time':Time, 'Value':Value})

For simplicity we will just calculate the average of the row itself, the row prior and the row posterior. So I would be looking for this result:

df
Time    Value
00:01   2.85 
00:02   3.43
00:03   3.8
00:04   3.23
00:05   2.53
00:06   1.47
00:07   2.87
00:08   2.53
00:09   3.6

Any help would be greatly appreciated.

yatu
  • 86,083
  • 12
  • 84
  • 139
nielsen
  • 383
  • 1
  • 6

1 Answers1

2

You can take the rolling.mean, setting center=True and min_periods=2 to consider the edges too:

df['Value'] = df.Value.rolling(3, min_periods=2, center=True).mean().round(2)

print(df)

    Time  Value
0  00:01   2.85
1  00:02   3.43
2  00:03   3.80
3  00:04   3.23
4  00:05   2.53
5  00:06   1.47
6  00:07   2.87
7  00:08   2.53
8  00:09   3.60
yatu
  • 86,083
  • 12
  • 84
  • 139
  • That worked! But I get the message: "__main__:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead" – nielsen Jun 15 '20 at 11:15
  • 1
    The usual cause is exaplained here https://stackoverflow.com/a/20627316/9698684 @nielsen – yatu Jun 15 '20 at 12:04