向一个numpy数组索引添加多个值

时间:2021-05-29 12:33:44

Simple Version: if I do this:

简单的版本:如果我这样做:

import numpy as np
a = np.zeros(2)
a[[1, 1]] += np.array([1, 1])

I get [0, 1] as an output. but I would like [0, 2]. Is that possible somehow, using implicit numpy looping instead of looping over it myself?

我得到[0,1]作为输出。但是我想要[0,2]。有没有可能,使用隐式的numpy循环而不是自己循环?

What-I-actually-need-to-do version:

What-I-actually-need-to-do版本:

I have a structured array that contains an index, a value, and some boolean value. I would like to sum those values at those indices, based on the boolean. Clearly that can be done with a simple loop, but it seems like it should be possible with clever numpy indexing (as above).

我有一个结构化数组,它包含一个索引、一个值和一些布尔值。我想根据布尔值对这些指标的值求和。显然,这可以通过一个简单的循环来完成,但是看起来应该可以使用聪明的numpy索引(如上所示)。

For example, I have an array with 5 elements that I want to populate from the array with values, indices, and conditions:

例如,我有一个包含5个元素的数组,我希望从数组中填充有值、索引和条件:

import numpy as np
size = 5
nvalues = 10
np.random.seed(1)
a = np.zeros(nvalues, dtype=[('val', float), ('ix', int), ('cond', bool)])
a = np.rec.array(a)
a.val = np.random.rand(nvalues)
a.cond = (np.random.rand(nvalues) > 0.3)
a.ix = np.random.randint(size, size=nvalues)

# obvious solution
obvssum = np.zeros(size)
for i in a:
    if i.cond:
        obvssum[i.ix] += i.val

# is something this possible?
doesntwork = np.zeros(size)
doesntwork[a[a.cond].ix] += a[a.cond].val

print(doesntwork)
print(obvssum)

Output:

输出:

[ 0.          0.          0.61927097  0.02592623  0.29965467]
[ 0.          0.          1.05459336  0.02592623  1.27063303]

I think what's happening here is if a[a.cond].ix were guaranteed to be unique, my method would work just fine, as noted in the simple example.

我认为这里发生的是如果。ix被保证是唯一的,我的方法会很好地工作,就像在这个简单的示例中提到的那样。

1 个解决方案

#1


5  

This is what the at method of NumPy ufuncs is for:

这就是NumPy ufuncs的at方法:

output = numpy.zeros(size)
numpy.add.at(output, a[a.cond].ix, a[a.cond].val)

#1


5  

This is what the at method of NumPy ufuncs is for:

这就是NumPy ufuncs的at方法:

output = numpy.zeros(size)
numpy.add.at(output, a[a.cond].ix, a[a.cond].val)