如何根据二维矩阵的第二列制作直方图,然后高效地计算总和?

问题描述 投票:0回答:1

矩阵就像 4000 列 x 1e8 行。

如何根据第二列制作直方图(1000个bin)并快速计算剩下的3999列的总和?

例如,bin 1 可能有 5 行,我需要 5x3999 值的总和。

bin2 可能有 0 行。

bin3 可能有 100 行,我需要 1000x3999 值的总和..

哪种Python方法最有效?

python numpy histogram
1个回答
0
投票

我的想法的草图(用 1000 行而不是 10^8 和 40 列而不是 4000)是:

import numpy as np
rng = np.random.default_rng()
x = rng.random((1000, 40))  # data without bin information
bins = [300, 200, 0, 1, 499]  # bin sizes (add up to 1000)

# assuming bins are specified by their size,
# calculate the indices of the last row of a bin
bins = np.cumsum(bins)-1

rowsums = np.sum(x, axis=1)
cumulative_sums = np.cumsum(rowsums)
binned_sums = cumulative_sums[bins]
binned_sums[1:] -= binned_sums[:-1]
binned_sums

这假设包含 bin 信息的列可以从数据中删除,并且与 bin 对应的行是连续的。如果问题根据我的评论更新,我很乐意更新答案。

© www.soinside.com 2019 - 2024. All rights reserved.