gpt4 book ai didi

python - Numpy 聚合到 bin 中,然后计算总和?

转载 作者:行者123 更新时间:2023-12-03 20:09:46 25 4
gpt4 key购买 nike

我有一个看起来像这样的矩阵:

M = [[1, 200],
[1.8, 100],
[2, 500],
[2.5, 300],
[3, 400],
[3.5, 200],
[5, 200],
[8, 100]]

我想按 bin 大小(应用于左列)对行进行分组,例如对于 bin 大小 2(第一个 bin 是 0-2 的值,第二个 bin 为 2-4,第三个 bin 为 4-6 等):
[[1, 200],
[1.8, 100],
----
[2, 500],
[2.5, 300],
[3, 400],
[3.5, 200],
----
[5, 200],
----
[8, 100]]

然后输出一个新矩阵,其中包含每组右列的总和:
[200+100, 500+300+400+200, 200, 100]

根据 bin_size 边界对每个值求和的有效方法是什么?

最佳答案

pandas :

做个 DataFrame然后使用整数除法来定义您的垃圾箱:

import pandas as pd

df = pd.DataFrame(M)
df.groupby(df[0]//2)[1].sum()

#0
#0.0 300
#1.0 1400
#2.0 200
#4.0 100
#Name: 1, dtype: int64

使用 .tolist()得到你想要的输出:
df.groupby(df[0]//2)[1].sum().tolist()
#[300, 1400, 200, 100]

numpy.bincount
import numpy as np

gp, vals = np.transpose(M)
gp = (gp//2).astype(int)

np.bincount(gp, vals)
#array([ 300., 1400., 200., 0., 100.])

关于python - Numpy 聚合到 bin 中,然后计算总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52953231/

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