将多个值添加到一个numpy数组索引 [英] Add multiple values to one numpy array index
问题描述
简单版本: 如果我这样做:
import numpy as np
a = np.zeros(2)
a[[1, 1]] += np.array([1, 1])
我得到[0, 1]
作为输出.但我想要[0, 2]
.使用隐式numpy循环而不是自己遍历它,是否可能以某种方式实现?
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?
我实际上需要做什么的版本:
我有一个结构化的数组,其中包含一个索引,一个值和一些布尔值.我想根据布尔值对那些索引处的值求和.显然,这可以通过一个简单的循环来完成,但是似乎可以通过聪明的numpy索引来实现(如上所述).
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).
例如,我有一个包含5个元素的数组,我希望使用值,索引和条件从该数组中填充该元素:
For example, I have an array with 5 elements that I want to populate from the array with values, indices, and conditions:
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)
输出:
[ 0. 0. 0.61927097 0.02592623 0.29965467]
[ 0. 0. 1.05459336 0.02592623 1.27063303]
我认为这里发生的是,如果保证a[a.cond].ix
是唯一的,那么我的方法就可以正常工作,如简单示例中所述.
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.
推荐答案
This is what the at
method of NumPy ufuncs is for:
output = numpy.zeros(size)
numpy.add.at(output, a[a.cond].ix, a[a.cond].val)
这篇关于将多个值添加到一个numpy数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!