1
>>> a = np.array([0, 0])
>>> a[[0, 0, 1, 1]] + [1, 2, 3, 4]
array([1, 2, 3, 4])
>>> a[[0, 0, 1, 1]] += [1, 2, 3, 4]
>>> a
array([2, 4])

I understand that a[[0, 0, 1, 1]] returns a view of a, whose first two elements point to a[0] and last two elements point to a[1]. Now what if I want to get a = [3, 7]? Which is to say, what is the easiest way to accomplish the following?

a = [0, 0]
indices = [0, 0, 1, 1]
values_to_add = [1, 2, 3, 4]
for i in indices:
    a[i] += values_to_add[i]
0

1 Answer 1

3

You may want to look into np.add.at

>>> np.add.at(a, [0,0,1,1], [1,2,3,4])
>>> a
array([3, 7])

Please note that often np.add.at can be replaced with np.bincount to gain a considerble speedup.

Finally, advanced indexing does not return views but copies. Assignment, however, is a different matter still. It wouldn't be very useful, if the assignment were made to a copy...

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

2 Comments

Thank you! I feel very dumb right now... In my defense, this doc is really hard to find: docs.scipy.org/doc/numpy/reference/generated/…
@MichaelMa No need to feel bad about it. It's not a stupid question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.