Skip to main content
 首页 » 编程设计

python之Numpy 聚合行和总和

2025年05月04日17birdshome

我有一个 Numpy 矩阵:

M = [[55, 5], 
 [56, 3], 
 [57, 7], 
 [58, 9], 
 [59, 3], 
 [60, 8], 
 [61, 1]]  

我想按 group_size 聚合(例如分成 3 组):

group_size = math.ceil(M.size/groups) # math.ceil(7/3) = 3 

每个聚合行的左值是组中第一个左值,右值是组中所有右值的总和。

预期输出:

R = [[55, 15], # 55 first left column value of first group, 15 sum of all right values in group  
 [58, 20], # 58 first left column value of second group, 20 sum of all right values in group 
 [61, 1]] # Third group consist only of one row, remainder 

有没有一种不用循环的 Numpy 解决这个问题的有效方法?

请您参考如下方法:

这是使用 NumPy 的一种方法:

n = 3 
x = M[::n, 0] 
y = np.add.reduceat(M[:, 1], np.arange(0, M.shape[0], n)) 
 
R = np.vstack((x, y)).T 
 
print(R) 
 
array([[55, 15], 
       [58, 20], 
       [61,  1]])