gpt4 book ai didi

python - Numpy 聚合行和总和

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:21 33 4
gpt4 key购买 nike

我有一个 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]])

关于python - Numpy 聚合行和总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53239224/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com