我正在寻找 np.add.at()
的二维版本。
预期行为如下。
augend = np.zeros((10, 10))
indices_for_dim0 = np.array([1, 5, 2])
indices_for_dim1 = np.array([5, 3, 1])
addend = np.array([1, 2, 3])
### some procedure substituting np.add.at ###
assert augend[1, 5] == 1
assert augend[5, 3] == 2
assert augend[2, 1] == 3
任何建议都会有所帮助!
最佳答案
您可以使用np.add.at
多维地,因为它是。 indices
参数在描述中包含以下内容:
... If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice
所以:
augend = np.zeros((10, 10))
indices_for_dim0 = np.array([1, 5, 2])
indices_for_dim1 = np.array([5, 3, 1])
addend = np.array([1, 2, 3])
np.add.at(augend, (indices_for_dim0, indices_for_dim1), addend)
更简单地说:
augend[indices_for_dim0, indices_for_dim1] += addend
如果您确实担心多维方面,并且您的被加数是普通的连续 C 顺序数组,则可以使用 ravel
和 ravel_multi_index
在一维 View 上执行操作:
indices = np.ravel_multi_index((indices_for_dim0, indices_for_dim1), augend.shape)
raveled = augend.ravel()
np.add.at(raveled, indices, addend)
关于python - `np.add.at` 转为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54284860/