无法通过slicing [duplicate]对numpy数组的每个元素执行多次算术运算

mhd8tkvw  于 2023-05-17  发布在  其他
关注(0)|答案(1)|浏览(108)

此问题已在此处有答案

Handling of duplicate indices in NumPy assignments(5个答案)
6天前关闭。
我有坐标表和Map。对于这些坐标中的每一个,我想在Map上添加10。然而,如果我尝试使用加等于运算符,它似乎只加一次,然后再也不会加了。如果我把它拉出来并加10,也会发生同样的行为,两种方式如下所示:

coordinates = np.asarray(np.random.randint(0,10,(1000,2)))
map_array = np.zeros((10,10))

map_array[coordinates[:,0], coordinates[:,1]] += 10 #If a coordinate is repeated, it doesn't add 10 to it again 
#map_array[coordinates[:,0], coordinates[:,1]] = map_array[coordinates[:,0], coordinates[:,1]] + 10 #same as above

map_array的输出:

[[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]

然而,当我迭代每个坐标并以这种方式向每个坐标添加10时,它似乎工作得很好。

for i in coordinates[:]:
    map_array[i[0], i[1]] +=10

map_array的输出:

[[110.,  90., 160.,  90.,  70.,  70., 140., 110.,  70.,  90.],
[ 90., 130.,  90.,  70., 130., 110., 130., 100., 120.,  90.],
[140., 100., 110., 110., 120.,  60., 140., 110.,  90.,  70.],
[120.,  90., 130., 110., 120.,  90., 100., 170., 100., 100.],
[160., 120., 130., 110., 130.,  80., 140.,  80., 180.,  70.],
[160., 160., 120., 100., 110.,  90.,  90.,  80., 120., 110.],
[120., 100., 120.,  80.,  90., 130., 130.,  60.,  90.,  90.],
[120.,  80., 160., 110., 100., 150., 130., 150., 120., 160.],
[160.,  80.,  90.,  30.,  90.,  80.,  40.,  80., 120., 160.],
[130., 120.,  80.,  90.,  80., 160., 130., 180., 100., 130.]]

我认为问题在于numpy不想多次选择同一个索引,因为如果我这样做:

coordinates = np.asarray(np.random.randint(0,10,(10,2)))
map_array = np.zeros((10,10))

map_array[coordinates[:,0], coordinates[:,1]] += 10 #only adds once

坐标输出:

[[6, 1],
[1, 7],
[5, 5],
[5, 0],
[5, 4],
[7, 3],
[5, 6],
[6, 3],
[3, 2],
[0, 7]]

Map输出:

[[ 0.,  0.,  0.,  0.,  0.,  0.,  0., 10.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0., 10.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0., 10.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
[10.,  0.,  0.,  0., 10., 10., 10.,  0.,  0.,  0.],
[ 0., 10.,  0., 10.,  0.,  0.,  0.,  0.,  0.,  0.],
[ 0.,  0.,  0., 10.,  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.]]

我们看到它不是将所有元素都设置为10。有没有办法不遍历每个元素?我想使用Numpy内置的速度。

tvz2xvvm

tvz2xvvm1#

看来这里已经解决了:https://stackoverflow.com/a/73958805
在我的例子中函数是

np.add.at(map_array,(coordinates[:,0],coordinates[:,1]),10)

相关问题