This question already has an answer here:
这个问题在这里已有答案:
- Increment Numpy array with repeated indices 4 answers
增加Numpy数组,重复索引4个答案
I have an array:
我有一个数组:
a = np.array([0,0,0,0,0,0])
I want to add some other array into each index of a, while the index can appear more than one times. I want to get the some of each index. I write:
我想在a的每个索引中添加一些其他数组,而索引可以出现多次。我想获得每个索引的一些内容。我写:
a[np.array([1,2,2,1,3])] += np.array([1,1,1,1,1])
but get a to be:
但得到一个:
array([0, 1, 1, 1, 0, 0])
But what I want is to get:
但我想要的是得到:
array([0, 2, 2, 1, 0, 0])
How to implement this in numpy without for loop?
如何在没有for循环的情况下实现这个numpy?
4 个解决方案
#1
9
Using pure numpy
, AND avoiding a for loop:
使用纯numpy,并避免for循环:
np.add.at(a, np.array([1,2,2,1,3]), np.array([1,1,1,1,1]))
Output:
>>> a = np.array([0,0,0,0,0,0])
>>> np.add.at(a, np.array([1,2,2,1,3]), np.array([1,1,1,1,1]))
>>> a
array([0, 2, 2, 1, 0, 0])
Please note, this does in-place substitution. This is what is desired by you, but it may not be desired by future viewers. Hence the note :)
请注意,这会进行就地替换。这是您所期望的,但未来的观众可能并不希望这样。因此注意:)
#2
1
You could always just iterate yourself. Something like:
你总是可以自己迭代。就像是:
for i in [1,2,2,1,3]:
a[i] += 1
#3
1
I don't know of a clever numpy vectorized way to do this... the best I can come up with is:
我不知道一个聪明的numpy矢量化方式来做到这一点...我能想到的最好的是:
>>> indices = np.array([1,2,2,1,3])
>>> values = np.array([1,1,1,1,1])
>>> a = np.array([0,0,0,0,0,0])
>>> for i, ix in enumerate(indices):
... a[ix] += values[i]
...
>>> a
array([0, 2, 2, 1, 0, 0])
#4
1
You can do something like (assuming for each index there is a correlated value):
您可以执行类似的操作(假设每个索引都有相关值):
a = np.array([0,0,0,0,0,0])
idxs = np.array([1,2,2,1,3])
vals = np.array([1,1,1,1,1])
for idx, val in zip(idxs,vals):
a[idx] += val
#1
9
Using pure numpy
, AND avoiding a for loop:
使用纯numpy,并避免for循环:
np.add.at(a, np.array([1,2,2,1,3]), np.array([1,1,1,1,1]))
Output:
>>> a = np.array([0,0,0,0,0,0])
>>> np.add.at(a, np.array([1,2,2,1,3]), np.array([1,1,1,1,1]))
>>> a
array([0, 2, 2, 1, 0, 0])
Please note, this does in-place substitution. This is what is desired by you, but it may not be desired by future viewers. Hence the note :)
请注意,这会进行就地替换。这是您所期望的,但未来的观众可能并不希望这样。因此注意:)
#2
1
You could always just iterate yourself. Something like:
你总是可以自己迭代。就像是:
for i in [1,2,2,1,3]:
a[i] += 1
#3
1
I don't know of a clever numpy vectorized way to do this... the best I can come up with is:
我不知道一个聪明的numpy矢量化方式来做到这一点...我能想到的最好的是:
>>> indices = np.array([1,2,2,1,3])
>>> values = np.array([1,1,1,1,1])
>>> a = np.array([0,0,0,0,0,0])
>>> for i, ix in enumerate(indices):
... a[ix] += values[i]
...
>>> a
array([0, 2, 2, 1, 0, 0])
#4
1
You can do something like (assuming for each index there is a correlated value):
您可以执行类似的操作(假设每个索引都有相关值):
a = np.array([0,0,0,0,0,0])
idxs = np.array([1,2,2,1,3])
vals = np.array([1,1,1,1,1])
for idx, val in zip(idxs,vals):
a[idx] += val