[英]How to add elements to a 2D array using python fancy indexing?
我正在用 python 編寫一個程序,我想盡可能地將它向量化。 我有以下變量
(L,T)
二維零點E
數組。(N,)
數組w
。(A,)
的數組index
(A,)
其值為0
到N-1
之間的整數。 這些值是唯一的。w
( (A,)
) 相同的數組labels
,其值為0
到L-1
之間的整數。 這些值不一定是唯一的。0
和T-1
之間的整數t
。 我們想將索引index
處的w
值添加到行labels
和列t
處的數組E
中。 我使用了以下代碼:
E[labels,t] += w[index]
但是這種方法並沒有給出想要的結果。 例如,
import numpy as np
E = np.zeros([10,1])
w = np.arange(0,100)
index = np.array([1,3,4,12,80])
labels = np.array([0,0,5,5,2])
t = 0
E[labels,t] += w[index]
給
array([[ 3.],
[ 0.],
[80.],
[ 0.],
[ 0.],
[12.],
[ 0.],
[ 0.],
[ 0.],
[ 0.]])
但正確的答案是
array([[ 4.],
[ 0.],
[80.],
[ 0.],
[ 0.],
[16.],
[ 0.],
[ 0.],
[ 0.],
[ 0.]])
有沒有辦法在不使用 for 循環的情況下實現這種行為?
我意識到我可以使用這個: np.add.at(E,[labels,t],w[index])
但它給了我這個警告:
FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.
從一個類似的問題中提取,您可以使用np.bincount()來實現您的目標:
import numpy as np
import time
E = np.zeros([10,1])
w = np.arange(0,100)
index = np.array([1,3,4,12,80])
labels = np.array([0,0,5,5,2])
t = 0
# --------- Using np.bincount()
start = time.perf_counter()
for _ in range(10000):
E = np.zeros([10,1])
values = w[index]
result = np.bincount(labels, values, E.shape[0])
E[:, t] += result
print("Bin count time: {}".format(time.perf_counter() - start))
print(E)
# --------- Using for loop
for _ in range(10000):
E = np.zeros([10,1])
for i, in_ in enumerate(index):
E[labels[i], t] += w[in_]
print("For loop time: {}".format(time.perf_counter() - start))
print(E)
給出:
Bin count time: 0.045003452
[[ 4.]
[ 0.]
[80.]
[ 0.]
[ 0.]
[16.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]]
For loop time: 0.09853353699999998
[[ 4.]
[ 0.]
[80.]
[ 0.]
[ 0.]
[16.]
[ 0.]
[ 0.]
[ 0.]
[ 0.]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.