如何计算 pandas 中前N行的累积和? [英] How to compute cumulative sum of previous N rows in pandas?

查看:69
本文介绍了如何计算 pandas 中前N行的累积和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在和熊猫一起工作,但是我没有太多经验.我有以下DataFrame:

I am working with pandas, but I don't have so much experience. I have the following DataFrame:

          A
0       NaN
1      0.00
2      0.00
3      3.33
4     10.21
5      6.67
6      7.00
7      8.27
8      6.07
9      2.17
10     3.38
11     2.48
12     2.08
13     6.95
14     0.00
15     1.75
16     6.66
17     9.69
18     6.73
19     6.20
20     3.01
21     0.32
22     0.52

,我需要计算前11行的累积总和.如果以前少于11,则假定它们为0.

and I need to compute the cumulative sum of the previous 11 rows. When there is less than 11 previously, they remaining are assumed to be 0.

        B
0     NaN
1    0.00
2    0.00
3    0.00
4    3.33
5    13.54
6    20.21
7    27.20
8    35.47
9    41.54
10    43.72
11   47.09
12   49.57 
13   51.65
14   58.60
15   58.60
16   57.02
17   53.48
18   56.49
19   56.22
20   54.16
21   51.10
22   49.24

我尝试过:

df['B'] = df.A.cumsum().shift(-11).fillna(0)

但是,这并没有达到我想要的,但是这正在旋转累积总和的结果.我该如何实现?

However, this is not achieving what I want, but this is rotating the result of a cumulative sum. How can I achieve this?

推荐答案

致电

Call rolling with min_periods=1 and window=11 and sum:

In [142]:
df['A'].rolling(min_periods=1, window=11).sum()

Out[142]:
0       NaN
1      0.00
2      0.00
3      3.33
4     13.54
5     20.21
6     27.21
7     35.48
8     41.55
9     43.72
10    47.10
11    49.58
12    51.66
13    58.61
14    55.28
15    46.82
16    46.81
17    49.50
18    47.96
19    48.09
20    48.93
21    45.87
22    43.91
Name: A, dtype: float64

这篇关于如何计算 pandas 中前N行的累积和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆