4

Suppose we have three 1-D arrays:

  • A (say of length 5),
  • B (the same length, 5 in the example)
  • C (much longer, say of length 100)

C is initially filled with zeros. A gives indices of C elements which should be changed (they may repeat), and B gives values which should be added to initial zeros of C. For example, if A = [1, 3, 3, 3, 29] and B = [2, 3, 4, 2, 3], C[1] should become 2, C[3] - 9, C[29] - 3; all other C elements should remain 0. I've written it as a for-loop:

for i in range(len(A) - 1):
    C[A[i]] = C[A[i]] + B[i]

But is there a more efficient way to do the same in numpy in the vector form?

1
  • 2
    I don't think you mean len(A)-1; that will skip the last element (29 & 3), as range doesn't include the upper bound. range(3) == [0,1,2]. Commented Aug 29, 2013 at 15:36

1 Answer 1

3

I think you might be able to use bincount, at least for the 1-D case:

>>> A = np.array([1,3,3,3,29])
>>> B = np.array([2,3,4,2,3])
>>> np.bincount(A, B)
array([ 0.,  2.,  0.,  9.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  3.])

(Aside: duplicated values when using numpy indexing can behave very strangely, and it's very easy to be led astray by the behaviour you see in simple cases. I avoid them entirely, as the behaviour is almost never what I want.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.