[英]Perform operation on elements of numpy array using indexes list
我有numpy數組和兩個python索引列表,它們的位置將數組元素增加一。 numpy是否有一些方法可以向量化此操作而不使用for
循環?
我目前執行緩慢:
a = np.zeros([4,5])
xs = [1,1,1,3]
ys = [2,2,3,0]
for x,y in zip(xs,ys): # how to do it in numpy way (efficiently)?
a[x,y] += 1
print(a)
輸出:
[[0. 0. 0. 0. 0.]
[0. 0. 2. 1. 0.]
[0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0.]]
np.add.at
可以做到這一點,只需將兩個索引作為單個2D數組/列表傳遞:
a = np.zeros([4,5])
xs = [1, 1, 1, 3]
ys = [2, 2, 3, 0]
np.add.at(a, [xs, ys], 1) # in-place
print(a)
array([[0., 0., 0., 0., 0.],
[0., 0., 2., 1., 0.],
[0., 0., 0., 0., 0.],
[1., 0., 0., 0., 0.]])
>>> a = np.zeros([4,5])
>>> xs = [1, 1, 1, 3]
>>> ys = [2, 2, 3, 0]
>>> a[[xs,ys]] += 1
>>> a
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 1., 0.],
[ 0., 0., 0., 0., 0.],
[ 1., 0., 0., 0., 0.]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.