我目前有2个阵列对应于坐标(X,Y),第三个数组对应于2d空间中此时的值。它被编码为不是矩阵,因为它是一个相当稀疏的矩阵(并非每个点都有一个值)。现在我想重建矩阵,以便用matplotlib.imshow()绘制值。
到目前为止,我最简单的方法是执行for循环,如下所示:
var productlist = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: [
{ "product": "GSPEN", "description": "Pen" },
{ "product": "GSTS", "description": "Tissue" },
]
});
$('#custom-templates .typeahead').typeahead(null, {
name: 'productlist',
display: 'product ',
source: local,
templates: {
empty: [
'<div class="empty-message">',
'unable to find any product that match the current query',
'</div>'
].join('\n'),
suggestion: Handlebars.compile('<div><strong>{{product}}</strong> – {{description}}</div>')
}
});
我的意思是,它并不可怕,但我担心大阵列。是否有一个函数将第1和第2个输入分别作为第1和第2个坐标,第3个输入作为这些坐标的值?或者会有类似的东西吗?
答案 0 :(得分:4)
对于你正在做的事情,你可以直接使用列表(不带)循环。示例 -
matrix[X,Y] = Z
演示 -
In [3]: X = [1, 1, 3, 5];
In [4]: Y = [2, 2, 3, 7];
In [5]: Z = [0.3, -0.5, 1, 1];
In [6]: matrix = np.zeros([10,10])
In [7]: matrix[X,Y] = Z
In [8]: matrix
Out[8]:
array([[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , -0.5, 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 1. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 1. , 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. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. , 0. ]])
In [9]: matrix1 = np.zeros([10,10])
In [10]: for i in range(len(Z)):
....: matrix1[X[i],Y[i]] = Z[i]
In [13]: (matrix1 == matrix).all() #Just to show its equal to OP's `for` loop method.
Out[13]: True
时间测试 -
In [24]: X = np.arange(1000)
In [25]: Y = np.arange(1000)
In [26]: Z = np.random.rand(1000)
In [27]: %%timeit
....: matrix = np.zeros([1000,1000])
....: matrix[X,Y] = Z
....:
1000 loops, best of 3: 834 µs per loop
In [28]: %%timeit
....: matrix1 = np.zeros([1000,1000])
....: for i in range(len(Z)):
....: matrix1[X[i],Y[i]] = Z[i]
....:
The slowest run took 6.47 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 1.43 ms per loop
当处理大型数组(并且Z很大)时,向量化方法会更快。
如果Z很小,那么使用for
循环方法会更快。