python - 添加到 numpy 数组的 View

标签 python numpy

>>> a = np.array([0, 0])
>>> a[[0, 0, 1, 1]] + [1, 2, 3, 4]
array([1, 2, 3, 4])
>>> a[[0, 0, 1, 1]] += [1, 2, 3, 4]
>>> a
array([2, 4])

据我了解a[[0, 0, 1, 1]]返回 a 的 View ,其前两个元素指向 a[0]最后两个元素指向 a[1] 。现在如果我想得到 a = [3, 7] 该怎么办? ?也就是说,完成以下任务的最简单方法是什么?

a = [0, 0]
indices = [0, 0, 1, 1]
values_to_add = [1, 2, 3, 4]
for i in indices:
    a[i] += values_to_add[i]

最佳答案

您可能想查看np.add.at

>>> np.add.at(a, [0,0,1,1], [1,2,3,4])
>>> a
array([3, 7])

请注意,通常可以将 np.add.at 替换为 np.bincount 以获得相当大的加速。

最后,高级索引不返回 View ,而是返回副本。然而,分配仍然是另一回事。如果分配给副本,这不会很有用...

关于python - 添加到 numpy 数组的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49608041/

相关文章:

numpy - 使用封闭路径切片 numpy 数组

python - 如何在 Python 中删除字符串中的任何 URL

python - Python中exit()和sys.exit()的区别

python - 如何摆脱数组中的内置引用并将其保存到文件中

python - 如何访问python列表列表中的列

python - 如何附加到 numpy 数组而不将结果重新分配给新变量?

Python 小数范围() 逐步值

python - 它会返回行数吗?

numpy - Keras(Numpy 输入)TypeError : Error converting shape to a TensorShape: int() argument must be a string, 类字节对象或数字,而不是 'tuple'

python - 制作一个可以接受各种形状参数的函数