user6162407 user6162407 - 4 months ago 17
Python Question

Row is sum of 3 latest values

df = pd.DataFrame({'values':[2,6,1,5,8,9]})


I'm trying to create a new rom called
sum
that is the sum of the 3 latest values. So it would return this
[np.nan, np.nan, 9, 12, 14, 22]

Answer

Use rolling with Rolling.sum:

print (df.rolling(3).sum())
   values
0     NaN
1     NaN
2     9.0
3    12.0
4    14.0
5    22.0

Or:

print (df['values'].rolling(3).sum())
0     NaN
1     NaN
2     9.0
3    12.0
4    14.0
5    22.0
Name: values, dtype: float64

df['sum'] = df['values'].rolling(3).sum()
print (df)
   values   sum
0       2   NaN
1       6   NaN
2       1   9.0
3       5  12.0
4       8  14.0
5       9  22.0

Docs.

Comments