python - numpy 数组指标操作

标签 python arrays 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]])

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

最佳答案

这是一种方式。计数算法 courtesy of @AlexRiley .

有关 imginds 的相对大小的性能影响,请参阅 @PaulPanzer's answer .

# 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]])

关于python - numpy 数组指标操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50594318/

相关文章:

python - 如何将包含随机数的函数应用于 python 中的 numpy 数组的行?

python - 在单循环中循环python dict中的多个键值对

Python/Flask : How to tell how long a user spends on a page?(数据输入/时间日志应用程序)

python - 在旋转排序数组中查找最小值的回收数组解决方案

java - 二维数组和用户输入

pandas - numpy 数组的维度不匹配

python - 在 Python 中使用 bool 值进行索引如何工作?

c++ - 通过 C++ 中的类传递二维数组

c - C 中的打印数组函数仅打印第一个元素

python - 距行中第一个非空元素的距离的 numpy 矩阵