python - 尝试用 Pandas 生成rolling_sum

标签 python pandas

我有一个简单的dataFrame,其中包含常规示例:

dates = pd.date_range('20150101', periods=6)
df = pd.DataFrame([1,2,3,4,5,6], index=dates, columns=list('A'))
df.loc[:,'B'] = 0
df.iloc[0,1] =10
df


Out[119]:
            A   B
2015-01-01  1   10
2015-01-02  2   0
2015-01-03  3   0
2015-01-04  4   0
2015-01-05  5   0
2015-01-06  6   0

我想做的是使用 Pandas 中的 rolling_sum 函数在 B 列中创建值,以便得到下表:

            A   B
2015-01-01  1   11
2015-01-02  2   13
2015-01-03  3   16
2015-01-04  4   20
2015-01-05  5   25
2015-01-06  6   31

也就是说,B(i+1) = A(i+1) + B(i) - 请注意,B(0) 处有一个特殊情况,因为初始值为10.我尝试使用以下内容,但给出了错误的答案:

df.B = pd.rolling_sum(df.A + df.B, 1)

最佳答案

尝试expanding_sum :

In [15]: df
Out[15]: 
            A   B
2015-01-01  1  10
2015-01-02  2   0
2015-01-03  3   0
2015-01-04  4   0
2015-01-05  5   0
2015-01-06  6   0

In [16]: df.B = pd.expanding_sum(df.A) + df.B[0]

In [17]: df
Out[17]: 
            A   B
2015-01-01  1  11
2015-01-02  2  13
2015-01-03  3  16
2015-01-04  4  20
2015-01-05  5  25
2015-01-06  6  31

关于python - 尝试用 Pandas 生成rolling_sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33053269/

相关文章:

python - 绘制调查中的分组信息

Python Pandas - 从 csv 文件创建时间序列

python Pandas : Wide format to long format but differently - similar to reverse dummy columns

python - 将 Numpy 数组从 (3, 2, 3) reshape 为 (3, 3, 2)

python - 使用 os.scandir 进行文件夹搜索

python - 如何让 PyQt4 与 PyCharm 一起工作

python-3.x - 创建所有列中包含连续 NaN 值的元组列表

python - Pandas 重采样错误?

python - 将字符串和整数分割为特定长度的python

python - 如何添加额外的列参数以从收件箱 gammu 插入到 Sentitems 上?