如何在 pandas 中一次对 `n` 行进行求和?

How do I perform a summation of `n` rows at a time in pandas?

给定一个数据框

     A
0   14
1   59
2   38
3   40
4   99
5   89
6   70
7   64
8   84
9   40
10  30
11  94
12  65
13  29
14  48
15  26
16  80
17  79
18  74
19  69

这个数据框有 20 列。我想一次对 n=5 行进行分组并将它们相加。所以,我的输出看起来像这样:

     A
0  250
1  347
2  266
3  328 

df.rolling_sum 无济于事,因为它不允许您在求和时改变步幅。

还有什么其他方法可以做到这一点?

假设您的索引是连续的,您可以对 df.index 执行整数除法,然后按索引分组。

对于上面的df,你可以这样做:

df.index // 5
# Int64Index([0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3], dtype='int64')

得到最终答案只是多了一步,使用df.groupby and dfGroupBy.sum:

df.groupby(df.index // 5).sum()

     A
0  250
1  347
2  266
3  328

如果您没有 RangeIndex,请先使用 df.reset_index,然后再分组。

df.set_index(df.index // 5).sum(level=0)

如果您可以使用求和而不是系列来管理 ndarray(无论如何您总是可以再次构建系列),则可以使用 np.add.reduceat

np.add.reduceat(df.A.values, np.arange(0, df.A.size, 5))

在这种情况下 returns

array([250, 347, 266, 328])