使用分区列方式汇总 DataFrame

Summarizing DataFrame using partitioned columnwise means

我想要一个一百万行长的数据框,并对其进行总结,所以我采用每块 20 行的列均值。有没有简单的方法来做到这一点?

    data = np.array([])
    result2 = np.split(result,96158)
    for each in range(len(result2)):
        data = np.append(data, np.array(result2[each].mean()))

这可行,但我不喜欢它,假设长度为 96158*20

这里还有一种方法是用groupby根据整数除法//然后.agg('mean').

df = pd.DataFrame(np.random.randn(50,2), columns=list('AB'))
df

         A       B
0  -0.6679 -0.3786
1   0.4253  1.0187
2   0.6159 -1.2768
3  -1.0202 -0.1413
4   0.2444  0.4939
5  -0.2606  0.1346
6  -1.2305  0.6479
7   0.2113 -1.0190
..     ...     ...
42 -0.0498 -1.3164
43  0.6948  0.5469
44  0.2718  0.2487
45 -2.9541 -0.9083
46 -0.5636 -0.4476
47 -0.1167  1.1087
48 -0.3220 -3.1022
49 -0.6414 -0.2629

[50 rows x 2 columns]

# the integer division
df.index//20

Int64Index([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
            2, 2, 2, 2, 2, 2],
           dtype='int64')


df.groupby(df.index//20).agg('mean')

        A       B
0 -0.9882 -0.0433
1 -2.4081  1.5017
2 -4.2048 -3.3826