持续更新 python 中最后 5 个数据集的聚合

Continuous update of Aggregation of last 5 data sets in python

我需要添加一个聚合最后 5 条数据的新功能。当它添加第 6 个数据时,它应该忘记第一个数据并只考虑最后 5 个数据集,如下所示。这是虚拟数据框,new_feature 是预期的输出。

id    feature    new_feature

1       a            a
2       b            a+b
3       c            a+b+c
4       d            a+b+c+d
5       e            a+b+c+d+e
6       f            b+c+d+e+f
7       g            c+d+e+f+g

使用 Series.rollingmin_periods=1 参数和 sum:

df = pd.DataFrame({'feature':[1,2,4,5,6,2,3,4,5]})
df['new_feature'] = df['feature'].rolling(5, min_periods=1).sum()
print (df)
   feature  new_feature
0        1          1.0
1        2          3.0
2        4          7.0
3        5         12.0
4        6         18.0
5        2         19.0
6        3         20.0
7        4         20.0
8        5         20.0