numpy数组指示器操作

ela*_*sha 4 python arrays numpy

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

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

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

操作:

>>> img[inds[:,1], inds[:,0]] += 1
Run Code Online (Sandbox Code Playgroud)

结果:

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

预期结果:

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

有人知道如何解决这个问题吗?优选地,不使用循环的快速方法.

jpp*_*jpp 6

这是一种方式.计数算法由@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]])
Run Code Online (Sandbox Code Playgroud)


mir*_*ulo 5

您可以使用numpy.add.at一些操作来准备索引.

np.add.at(img, tuple(inds[:, [1, 0]].T), 1)
Run Code Online (Sandbox Code Playgroud)

如果你有更大的inds阵列,这种方法应该保持快速...(虽然保罗Panzer的解决方案更快)