简体   繁体   中英

pandas dataframe rolling window with groupby

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? Eg 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?

f = lambda x: x.rolling(2).sum().shift()
df['c'] = df.groupby('a').b.apply(f)

df

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM