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

时间:2022-12-29 18:44:57

Suppose I have a 2D array, table of shape m x n.

假设我有一个2D数组,形状表m x n。

Suppose I have a 1D array, col_indices of shape m, and range [0,n) in terms of the values.

假设我有一个1D数组,形状为m的col_indices,以及值的范围[0,n)。

Finally, suppose I have a value array, vals of shape u, indexed by i.

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


In pseudo code, I would like to write:

在伪代码中,我想写:

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

And, written out manually:

并且,手动写出:

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 ] ]

1 个解决方案

#1


1  

Use advanced indexing by replacing the row slice with an integer array:

通过使用整数数组替换行切片来使用高级索引:

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

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

#1


1  

Use advanced indexing by replacing the row slice with an integer array:

通过使用整数数组替换行切片来使用高级索引:

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

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