[英]Numpy tuple-index based 2d array additive assignment
If we have a 2d array, for example 100x100, and we want to add values to it based on their coordinates, how can we avoid overwriting the previous coordinate value's value? 如果我们有一个二维数组,例如100x100,并且我们想根据它们的坐标为它添加值,我们怎样才能避免覆盖先前坐标值的值?
import numpy as np
vm_map = np.zeros((100,100))
a = np.array([[0,1], [10,10], [40,40], [40,40]])
vm_map[tuple(a.T)] = vm_map[tuple(a.T)] + [1,.5,.3, .2]
print(vm_map[40,40])
We would like this code block to print .5, adding the two [40,40] coordinates, instead it prints .2, as that was the last value it received at that coordinate. 我们希望这个代码块打印.5,添加两个[40,40]坐标,而不是打印.2,因为那是它在该坐标处接收的最后一个值。
You could use np.add.at
for an in-place addition at the specified coordinates: 您可以使用
np.add.at
在指定坐标处进行就地添加:
vm_map = np.zeros((100,100))
a = np.array([[0,1], [10,10], [40,40], [40,40]])
np.add.at(vm_map, tuple(zip(*a)), [1,.5,.3, .2])
print(vm_map)
array([[0., 1., 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.]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.