Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 different). Has somebody got a solution for such a problem which avoids using for loops? Is it a bug in numpy? Thanks in advance

like image 215
fightthewar Avatar asked Dec 27 '22 16:12

fightthewar


2 Answers

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.

like image 145
Ferdinand Beyer Avatar answered Jan 02 '23 06:01

Ferdinand Beyer


or you can use bincount():

a=numpy.zeros(5)
idx = numpy.bincount([0,0,0,1,1,3,3])
a[:len(idx)]+=idx
like image 32
HYRY Avatar answered Jan 02 '23 04:01

HYRY