12

假设您有一个需要汇总在一起的值数组

d = [1,1,1,1,1]

和第二个数组,指定需要将哪些元素相加

i = [0,0,1,2,2]

结果将存储在一个新的 size 数组中max(i)+1。因此,例如i=[0,0,0,0,0],相当于将所有元素相加d并将结果存储在0新数组 size的位置1

我尝试使用

c = zeros(max(i)+1)
c[i] += d

但是,该+=操作仅将每个元素添加一次,从而给出了意想不到的结果

[1,1,1]

代替

[2,1,2]

如何正确实现这种求和?

4

5 回答 5

13

如果我正确理解了这个问题,那么有一个快速的功能(只要数据数组是 1d)

>>> i = np.array([0,0,1,2,2])
>>> d = np.array([0,1,2,3,4])
>>> np.bincount(i, weights=d)
array([ 1.,  2.,  7.])

np.bincount 返回所有整数 range(max(i)) 的数组,即使某些计数为零

于 2010-09-11T01:00:49.720 回答
3

Juh_ 的评论是最有效的解决方案。这是工作代码:

import numpy as np
import scipy.ndimage as ni

i = np.array([0,0,1,2,2])
d = np.array([0,1,2,3,4])

n_indices = i.max() + 1
print ni.sum(d, i, np.arange(n_indices))
于 2014-06-17T10:36:15.057 回答
2
def zeros(ilen):
 r = []
 for i in range(0,ilen):
     r.append(0)

i_list = [0,0,1,2,2]
d = [1,1,1,1,1]
result = zeros(max(i_list)+1)

for index in i_list:
  result[index]+=d[index]

print result
于 2010-08-31T04:53:55.807 回答
2

此解决方案对于大型数组应该更有效(它迭代可能的索引值而不是 的单个条目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.]
于 2010-09-02T15:42:08.897 回答
0

在一般情况下,当您想按标签对子矩阵求和时,可以使用以下代码

import numpy as np
from scipy.sparse import coo_matrix

def labeled_sum1(x, labels):
     P = coo_matrix((np.ones(x.shape[0]), (labels, np.arange(len(labels)))))
     res = P.dot(x.reshape((x.shape[0], np.prod(x.shape[1:]))))
     return res.reshape((res.shape[0],) + x.shape[1:])

def labeled_sum2(x, labels):
     res = np.empty((np.max(labels) + 1,) + x.shape[1:], x.dtype)
     for i in np.ndindex(x.shape[1:]):
         res[(...,)+i] = np.bincount(labels, x[(...,)+i])
     return res

第一种方法使用稀疏矩阵乘法。第二个是user333700答案的概括。两种方法的速度相当:

x = np.random.randn(100000, 10, 10)
labels = np.random.randint(0, 1000, 100000)
%time res1 = labeled_sum1(x, labels)
%time res2 = labeled_sum2(x, labels)
np.all(res1 == res2)

输出:

Wall time: 73.2 ms
Wall time: 68.9 ms
True
于 2015-06-02T10:40:32.823 回答