gpt4 book ai didi

numpy - numpy.add.at 可以与二维索引一起使用吗?

转载 作者:行者123 更新时间:2023-12-05 08:52:32 31 4
gpt4 key购买 nike

我有 2 个数组:
- image 是一个 NxN 数组,
- indices 是一个 Mx2 数组,其中最后一个维度将有效索引存储到 image 中。

我想在 indices 中每次出现该索引时在 image 中添加 1。

似乎 numpy.add.at(image, indices, 1) 应该可以解决问题,只是我无法让它对 image 执行二维索引:

image = np.zeros((5,5), dtype=np.int32)
indices = np.array([[1,1], [1,1], [3,3]])
np.add.at(image, indices, 1)
print(image)

结果:

[[0 0 0 0 0]
[4 4 4 4 4]
[0 0 0 0 0]
[2 2 2 2 2]
[0 0 0 0 0]]

期望的结果:

[[0 0 0 0 0]
[0 2 0 0 0]
[0 0 0 0 0]
[0 0 0 1 0]
[0 0 0 0 0]]

最佳答案

In [477]: np.add.at(x,(idx[:,0],idx[:,1]), 1)                                                          
In [478]: x
Out[478]:
array([[0., 0., 0., 0., 0.],
[0., 2., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0.]])

或等效

In [489]: np.add.at(x,tuple(idx.T), 1)                                                                 
In [490]: x
Out[490]:
array([[0., 0., 0., 0., 0.],
[0., 2., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0.]])

哪里:

In [491]: tuple(idx.T)                                                                                 
Out[491]: (array([1, 1, 3]), array([1, 1, 3]))
In [492]: x[tuple(idx.T)]
Out[492]: array([2., 2., 1.])

关于numpy - numpy.add.at 可以与二维索引一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56509600/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com