`np.add.at.公司`到二维数组

2024-10-03 00:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我在找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

任何建议都会有帮助!在


Tags: 版本addfornpzerossomeassertarray
2条回答

Oneliner公司:

np.add.at(augend, (indices_for_dim0, indices_for_dim1), addend)
augend
array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 3., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 2., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])

assert augend[1, 5] == 1
assert augend[5, 3] == 2
assert augend[2, 1] == 3
# No AssertionError

当对np.add.at使用2d数组时,indices必须是一个元组,其中tuple[0]包含所有第一个坐标,tuple[1]包含所有第二个坐标。在

您可以按原样多维使用^{}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)

更简单地说:

^{pr2}$

如果您真的很担心多维方面,并且augend是一个普通的连续C顺序数组,那么可以使用^{}和{a3}在1D视图上执行操作:

indices = np.ravel_multi_index((indices_for_dim0, indices_for_dim1), augend.shape)
raveled = augend.ravel()
np.add.at(raveled, indices, addend)

相关问题 更多 >