簡體   English   中英

如何使用python花式索引向二維數組添加元素?

[英]How to add elements to a 2D array using python fancy indexing?

我正在用 python 編寫一個程序,我想盡可能地將它向量化。 我有以下變量

  1. 具有形狀(L,T)二維零點E數組。
  2. 具有任意值的形狀(N,)數組w
  3. 形狀為(A,)的數組index (A,)其值為0N-1之間的整數。 這些值是唯一的。
  4. 形狀與w ( (A,) ) 相同的數組labels ,其值為0L-1之間的整數。 這些值不一定是唯一的。
  5. 0T-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM