【问题标题】:Can numpy.add.at be used with 2D indices?numpy.add.at 可以与 2D 索引一起使用吗?
【发布时间】:2019-06-08 19:42:05
【问题描述】:

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

我想在image 中为indices 中该索引的每次出现添加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]]

【问题讨论】:

  • 错误是什么?
  • 来自文档:If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice objects. indices 不是元组,是吗?
  • 您必须 1) 转置 indices 和 2) 将结果转换为 @hpaulj 指出的元组。
  • 是的,我阅读了文档,但我想我不明白它们的意思。转置索引似乎没有帮助。你能给我一个代码示例吗?谢谢!

标签: numpy numpy-ufunc


【解决方案1】:
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.])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2018-02-16
    • 2020-06-30
    相关资源
    最近更新 更多