user6162407
user6162407

Reputation: 267

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]

Upvotes: 3

Views: 52

Answers (2)

Divakar
Divakar

Reputation: 221584

With focus on performance, here's one approach using NumPy's 1D convolution -

np.append([np.nan]*2,np.convolve(df['values'],np.ones((3,)),'valid'))

Upvotes: 1

jezrael
jezrael

Reputation: 862851

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.

Upvotes: 3

Related Questions