Cumulative summation of a numpy array by index(按索引对numpy数组的累积求和)
问题描述
假设您有一个需要相加的值数组
Assume you have an array of values that will need to be summed together
d = [1,1,1,1,1]
第二个数组指定哪些元素需要相加
and a second array specifying which elements need to be summed together
i = [0,0,1,2,2]
结果将存储在大小为 max(i)+1
的新数组中.因此,例如 i=[0,0,0,0,0]
相当于将 d
的所有元素相加并将结果存储在位置 0
的大小为 1
的新数组.
The result will be stored in a new array of size max(i)+1
. So for example i=[0,0,0,0,0]
would be equivalent to summing all the elements of d
and storing the result at position 0
of a new array of size 1
.
我尝试使用
c = zeros(max(i)+1)
c[i] += d
但是,+=
操作只将每个元素添加一次,从而给出了
However, the +=
operation adds each element only once, thus giving the unexpected result of
[1,1,1]
而不是
[2,1,2]
如何正确实现这种求和?
How would one correctly implement this kind of summation?
推荐答案
这个解决方案对于大型数组应该更有效(它迭代可能的索引值而不是 i
的单个条目):
This solution should be more efficient for large arrays (it iterates over the possible index values instead of the individual entries of i
):
import numpy as np
i = np.array([0,0,1,2,2])
d = np.array([0,1,2,3,4])
i_max = i.max()
c = np.empty(i_max+1)
for j in range(i_max+1):
c[j] = d[i==j].sum()
print c
[1. 2. 7.]
这篇关于按索引对numpy数组的累积求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按索引对numpy数组的累积求和


- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 沿轴计算直方图 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01