我需要添加一个汇总最后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

关于python - 持续更新python中最后5个数据集的聚合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60350760/

10-12 17:50
查看更多