有个一个矩阵b,经过索引变换后得到bexp
b = np.asarray([[1, 2, 3, 4, 5, 6]])
bexp =b[:,[[2,3,4],[3,4,5]]] #索引变换
bexp
Out[56]:
array([[[3, 4, 5],
[4, 5, 6]]])
现在我想通过这个变换(index)以及bexp 计算原来a的部分元素值:
c = np.zeros_like(b)
np.add.at(c, (slice(None),[[2,3,4],[3,4,5]] ), bexp)
c
Out[60]: array([[ 0, 0, 3, 8, 10, 6]])
可以发现,3,4 这两个重复的位置被计算了两次,本来应该是4,5,现在变换回去却成了 8 10 ,就因为 add 进行了两次,这也就官方文档中说明的:
For addition ufunc, this method is equivalent to
`a[indices] += b`, except that results are accumulated for elements that
are indexed more than once.
但是如果我用 拥有缓冲的方法来进行估计原矩阵:
d = np.zeros_like(c)
d[(slice(None),[[2,3,4],[3,4,5]] )] += bexp
d
Out[67]: array([[0, 0, 3, 4, 5, 6]])
可以看到,参与索引运算的元素与原来矩阵的位置的值是相同的。