首页 > 解决方案 > numpy 数组指标操作

问题描述

我想通过给定的指标(x 和 y 轴)修改一个空位图。对于指标给出的每个坐标,该值应加一。

到目前为止一切似乎都很好。但是,如果我的指标数组中有一些类似的指标,它只会提高一次价值。

>>> img
array([[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]])

>>> inds
array([[0, 0],
       [3, 4],
       [3, 4]])

手术:

>>> img[inds[:,1], inds[:,0]] += 1

结果:

>>> img
    array([[1, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 1, 0]])

预期结果:

>>> img
    array([[1, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 2, 0]])

有人知道如何解决这个问题吗?最好是不使用循环的快速方法。

标签: pythonarraysnumpy

解决方案


这是一种方式。计数算法由@AlexRiley 提供

有关 和 的相对大小的性能影响imginds请参阅@PaulPanzer 的答案

# count occurrences of each row and return array
counts = (inds[:, None] == inds).all(axis=2).sum(axis=1)

# apply indices and counts
img[inds[:,1], inds[:,0]] += counts

print(img)

array([[1, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 2, 0]])

推荐阅读