python - 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]])
有人知道如何解决这个问题吗?最好是不使用循环的快速方法。
解决方案
这是一种方式。计数算法由@AlexRiley 提供。
有关 和 的相对大小的性能影响img
,inds
请参阅@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]])
推荐阅读
- javascript - 基于下拉值的 React-google-map 标记图标未显示正确的图标
- python - 为什么 Python 将 "bar" 中的 "foo" 评估为 False!= "baz"?
- algorithm - 范围查询如何与排序字符串表一起使用?
- azure - 用户访问查看 Microsoft Azure 中的自定义报告
- cuda - 如何为 CUDA 中的每个线程使用寄存器内存?
- python - 如何从 .aspx 页面中提取所有源代码?
- python - 正则表达式选择整行
- android - Android 模拟器超时
- flutter - Flutter firebase auth抛出平台异常未被try catch捕获
- jenkins - JENKINS 使用基本身份验证从 groovy 应用程序中抛出 403 禁止