1. 批量操作
1.1. 现象
import numpy as np
vec = np.zeros(10, int)
indices = np.array([0, 0])
vec[indices] += 1
print(vec)
上面代码的输出不是
[2 0 0 0 0 0 0 0 0 0]
而是
[1 0 0 0 0 0 0 0 0 0]
1.2. 原因
这是因为numpy.array的操作是并行操作,而非串行操作。如果是串行操作,则vec的第一个元素两次增加1,得到的是2。因为是并行操作,所以vec的第一个元素分别增加1,得到1,并回写。
1.3. 解决方法
import numpy as np
vec = np.zeros(10, int)
indices = np.array([0, 0])
value, counter = np.unique(indices, return_counts=True)
vec[indices] += counter
print(vec)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)