Indexing python array with a python array with redundant elements
I'm experiencing a problem with array indexing. Suppose you have an array a and another array b you want to use to use as index for a in order to assign some values to the position pointed by b elements.
a=numpy.zeros(5)
print a
[ 0. 0. 0. 0. 0.]
Now I would like to increase the second element twice
b=numpy.array([1,1])
a[b]+=1.
print a
[ 0. 1. 0. 0. 0.]
while I expected to have
[ 0. 2. 0. 0. 0.]
There are no problems if the array b has no redundancies (all values of its elements are differen开发者_运维百科t). Has somebody got a solution for such a problem which avoids using for loops? Is it a bug in numpy? Thanks in advance
When you use an integer array for indexing another array, NumPy cannot create an adequate view, since the resulting array may not be representable with strides. Therefore, it will return a copy:
>>> a = np.zeros(5)
>>> b = np.array([1, 1])
>>> c = a[b]
>>> c
array([ 0., 0.])
>>> c.base is a
False
When using this index with in-place operations like +=
, NumPy will interpret it differently than you expect. Instead of "Walk the index array and perform the operation on each element in turn", it will first select all values that are indexed by b
(in this case, just one element with index 1
), then perform the operation on these elements once.
or you can use bincount():
a=numpy.zeros(5)
idx = numpy.bincount([0,0,0,1,1,3,3])
a[:len(idx)]+=idx
You can try:
a += numpy.histogram(b, numpy.arange(len(a)+1))[0]
This will return a = array([ 0., 2., 0., 0., 0.])
精彩评论