python - `np.add.at` 到二维数组
问题描述
我正在寻找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
参数在描述中包含以下内容:
...如果第一个操作数有多个维度,则索引可以是数组的元组,如索引对象或切片
所以:
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
andravel_multi_index
在一维视图上执行操作:
indices = np.ravel_multi_index((indices_for_dim0, indices_for_dim1), augend.shape)
raveled = augend.ravel()
np.add.at(raveled, indices, addend)
推荐阅读
- postgresql - PostgreSQL 启动恢复
- javascript - Express - NodeJS - 错误:在将标头发送到客户端后无法设置标头
- oracle - 在 oracle 中从 CLOB 中通用解析 JSON
- c# - RazorEngine 渲染 ViewComponent 和 TagHelpers
- twincat - 将 FB1 传递给带有 FB2 的程序,这些程序想要使用 FB1 正在实现的接口
- python - 如何在 df 中创建一个新列并使用 shift 函数?
- java - Spring HATEOAS Hal Forms 不会将当前 GET 端点添加到模板部分
- ios - 使用 Web Inspector 从 MacBook Air 2020 调试 iOS Web 应用程序
- ios - 在子项目中重用来自父项目的 cocoapod
- java - JavaFX圆形线性渐变填充百分比