DikobrAz
DikobrAz

Reputation: 3717

Sum of indexed numpy arrays

Suppose I have an array of indices:

I=[0 1 2 3 0 3]

And array of values:

W=[w0, w1, w2, w3]

How can I create an array X using vectorized numpy expressions produced as follows:

X = np.zeros(I.max() + 1)
for i in range(len(I)):
   X[I[i]] += W[I[i]]

In the above example X=[w0+w0, w1, w2, w3+w3]

Upvotes: 0

Views: 50

Answers (1)

keepAlive
keepAlive

Reputation: 6665

Starting with reproducible objects

>>> I = np.r_[0, 1, 2, 3, 0, 3]
>>> W = np.r_[60, 50, 40, 30, 20, 10]
>>> M = W[I]

Then note that one has

>>> W[I]
array([60, 50, 40, 30, 60, 30])
>>> W[W[I]==W]
array([60, 50, 40, 30])
>>> np.unique(W[I], return_counts=True)[1]
array([2, 1, 1, 2])

Finally, what about doing

>>> W[M==W]*np.unique(M, return_counts=True)[1] #  X
array([120, 50, 40, 60])

Let's (almost) do that with strings

>>> W = np.array(['w0', 'w1', 'w2', 'w3', 'w4', 'w5'])
>>> M = W[I]
>>> M
array(['w0', 'w1', 'w2', 'w3', 'w0', 'w3'], dtype='|S2')
>>> W[M==W]
array(['w0', 'w1', 'w2', 'w3'], dtype='|S2')
>>> np.unique(W[I], return_counts=True)[1]
array([2, 1, 1, 2])

Which leads to mentally consider

>>> [2*'w0', 'w1', 'w2', 2*'w3']   

Upvotes: 1

Related Questions