【发布时间】:2019-03-01 17:24:54
【问题描述】:
我正在用 python 编写一个程序,我想尽可能地对其进行矢量化。我有以下变量
- 二维零数组
E,形状为(L,T)。 - 数组
w,形状为(N,),任意值。 - 数组
index,形状为(A,),其值是介于0和N-1之间的整数。这些值是独一无二的。 - 数组
labels,形状与w((A,))相同,其值为0和L-1之间的整数。 这些值不一定是唯一的。 -
0和T-1之间的整数t。
我们希望将索引index 处的w 的值添加到数组E 的行labels 和列t。我使用了以下代码:
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.
【问题讨论】:
-
很抱歉,
indices是什么?我想你的意思是index..对吗?? -
警告表明使用像
np.add.at(E, (labels, t), w[index])这样的元组,而不是传递list。
标签: python arrays numpy indexing