Add Values In Numpy Array Successively, Without Looping
Maybe has been asked before, but I can't find it. Sometimes I have an index I, and I want to add successively accordingly to this index to an numpy array, from another array. For e
Solution 1:
Use numpy.add.at
:
>>>import numpy as np>>>A = np.array([1,2,3])>>>B = np.array([10,20,30])>>>I = np.array([0,1,1])>>>>>>np.add.at(A, I, B)>>>A
array([11, 52, 3])
Alternatively, np.bincount
:
>>>A = np.array([1,2,3])>>>B = np.array([10,20,30])>>>I = np.array([0,1,1])>>>>>>A += np.bincount(I, B, minlength=A.size).astype(int)>>>A
array([11, 52, 3])
Which is faster?
Depends. In this concrete example add.at
seems marginally faster, presumably because we need to convert types in the bincount
solution.
If OTOH A
and B
were float
dtype then bincount
would be faster.
Solution 2:
You need to use np.add.at
:
A = np.array([1,2,3])
B = np.array([10,20,30])
I = np.array([0,1,1])
np.add.at(A, I, B)
print(A)
prints
array([11, 52, 3])
This is noted in the doc:
ufunc.at(a, indices, b=None)
Performs unbuffered in place operation on operand ‘a’ for elements specified by ‘indices’. For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once. For example, a[[0,0]] += 1 will only increment the first element once because of buffering, whereas add.at(a, [0,0], 1) will increment the first element twice.
Post a Comment for "Add Values In Numpy Array Successively, Without Looping"