将特定坐标增加到numpy数组中

3

我对numpy非常陌生,并且我想使用numpy来增加数组中特定位置的值(这样可以更快)。

具体而言,我有一个“信息”类数组中的坐标列表。

class info:
    def __init__(self, timestamp, position):
        self.timestamp = timestamp
        self.position = position

目前我是这样做的:

for data in datas:
    x = data.position[0]
    y = data.position[1]

    self.heatmap[x][y] += 1

"heatmap"也是一个大小为宽度和高度的numpy数组。 我想知道是否有更多“numpy”的方法来做这件事。 编辑:我要查找的是单词“indice”,抱歉。答案在这里:Increment given indices in a matrix

1
一个旁注。 "Data" 是一个复数词。它的单数形式是 "datum"。因此,for data in datas 应该是 for datum in data - Eli Korvigo
在所有这些中,numpy数组在哪里?“heatmap”是什么? - talonmies
抱歉,热力图是 np.zeros((width, height))。 - Pâris Douady
这不是那个特定问题的重复。我认为这个问题不是关于增加索引的。这个问题是关于在给定一组索引的情况下增加数组值的(根据问题中给出的示例),并基于短语“增加数组的特定位置”。 - uhoh
嗯,你说得对,但是其他问题中的方法正是我想要的。问题是我正在寻找一种快速的方法来执行它(以便for循环在C中执行)。 - Pâris Douady
1个回答

0
例如,您可以使用类似这样的东西吗?
import numpy as np
a = np.arange(16).reshape(4,4)
b = [0,0]
c = (1,1)
d = (np.array([2]),np.array([2]))
e = ([3],[3])
a[b] = 100  # b isn't a tuple so it doesn't work the way the others do
a[c] = 200
a[d] = 300
a[e] = 400
print a

[[100 100 100 100]
 [  4 200   6   7]
 [  8   9 300  11]
 [ 12  13  14 400]]

所以你可能会考虑

self.heatmap[tuple(data.position)] += 1

但是它会进行优化吗?也就是说,这个计算是在 C 中完成而不是在 Python 中完成的吗?(谈论 for 循环) - Pâris Douady
刚刚做了一些性能测试,不起作用。 - Pâris Douady
你要求“更numpy的方式”。在某些条件下,Numpy 可以比纯Python更快,因为它允许您调用用C编写的程序例程。但对于小数组,它通常根本不更快。 - uhoh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接