Python广播:使用一维向量作为二维数组一维索引

Python Broadcasting: Use 1D vector as index in one dimension of 2d array

假设我有一个 table 形状 m x n 的二维数组。

假设我有一个一维数组,col_indices 的形状为 m,值的范围为 [0,n)

最后,假设我有一个值数组 vals,形状为 u,由 i 索引。


在伪代码中,我想写:

table[:,col_ind[:]] += vals[i]

并且,手动写出:

t = [ [ 0,0,0]
      [ 0,0,0]
      [ 0,0,0] ]

c = [ 0, 1, 2 ]

v = [ 1, 10, 1000 ]

i = 1

# then f(t,c,v,i) where f is the broadcast function
f(t,c,v,i) outputs:

t = [ [ 10,  0,  0 ]
      [  0, 10,  0 ]
      [  0,  0, 10 ] ]

通过用整数数组替换行切片来使用advanced indexing

t[np.arange(c.size), c] = v[i]

t
#array([[10,  0,  0],
#       [ 0, 10,  0],
#       [ 0,  0, 10]])