如何根据 numpy 中的索引范围对元素求和?

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

想象我有这些数据:

开始 结束 价值
0 5 100
2 4 200
1 2 600

start 和 end 代表该值所在的范围。我需要根据范围对所有值求和。 想法是这样的:

100 100 100 100 100   <- because 100 is from index 0 to 5
+
0   0   200 200 0     <- because 200 is from index 2 to 4
+
0   600 0   0   0     <- because 600 is from index 1 to 2
=
100 700 300 300 100   <- summed result

我知道,使用 for 循环可以实现此行为,但如果我有数百万行,则性能会有所欠缺。有没有更好的解决方案,比如使用某种矢量化方法?
我最初尝试在 numpy 中解决这个问题,但如果有任何其他技术可以提供帮助,请告诉我。

python numpy vectorization
1个回答
0
投票

尝试使用 NumPy 的向量化运算:

import numpy as np

# Define your data
data = np.array([
    [0, 5, 100],
    [2, 4, 200],
    [1, 2, 600]
])

result = np.zeros(data[:, 1].max() + 1, dtype=int)

# Iterate over each row of the data and add the values to the result array

for row in data:
    result[row[0]:row[1] + 1] += row[2]

print(result)

输出:

[100 700 900 300 300 100]
© www.soinside.com 2019 - 2024. All rights reserved.