I can add a new column c
that is a sum of the last two values in b
as shown below...
df['c'] = df.b.rolling(window = 2).sum().shift()
df
a b c
0 1 3 NaN
1 1 0 NaN
2 0 6 3.0
3 1 0 6.0
4 0 0 6.0
5 1 7 0.0
6 0 0 7.0
7 0 7 7.0
8 1 4 7.0
9 1 2 11.0
...however, what if I want to group by a
first? E.g. I can do this:
df['c'] = df.groupby(['a'])['b'].shift(1) + df.groupby(['a'])['b'].shift(2)
Is there a more elegant way for summing a large number of shifts (1, 2, ...n) on a group?