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 different). 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With