pandas dataframe rolling window with groupby

2020-07-10 07:46发布

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?

1条回答
▲ chillily
2楼-- · 2020-07-10 08:02
f = lambda x: x.rolling(2).sum().shift()
df['c'] = df.groupby('a').b.apply(f)

df

enter image description here

查看更多
登录 后发表回答