gpt4 book ai didi

python - 带有groupby的 Pandas 数据框滚动窗口

转载 作者:太空狗 更新时间:2023-10-30 01:06:01 25 4
gpt4 key购买 nike

我可以添加一个新列 c,它是 b 中最后两个值的总和,如下所示...

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

...但是,如果我想先按a 分组怎么办?例如。我可以这样做:

df['c'] = df.groupby(['a'])['b'].shift(1) + df.groupby(['a'])['b']。移位(2)

是否有更优雅的方法来对一组中的大量类次(1、2、...n)求和?

最佳答案

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

df

enter image description here

关于python - 带有groupby的 Pandas 数据框滚动窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40701317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com