擅长:python、mysql、java
<p>我们可以用<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow noreferrer">^{<cd1>}</a>-</p>
<pre><code>M,N = u_x.max()+1,u_y.max()+1
ids = u_x*N+u_y
out = np.bincount(ids.ravel(),phase_space.ravel(),minlength=M*N).reshape(M,N)
</code></pre>
<p>在更通用的设置上运行示例-</p>
<pre><code>In [14]: u_x
Out[14]:
array([[1, 2, 1],
[0, 1, 4],
[0, 0, 0]])
In [15]: u_y
Out[15]:
array([[2, 1, 2],
[6, 0, 1],
[2, 6, 0]])
In [17]: phase_space
Out[17]:
array([[1, 1, 1],
[5, 1, 1],
[1, 1, 1]])
In [18]: out
Out[18]:
array([[1., 0., 1., 0., 0., 0., 6.],
[1., 0., 2., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0., 0., 0.]])
</code></pre>
<p>我们还可以利用稀疏矩阵,特别是在考虑记忆的情况下-</p>
<pre><code>from scipy.sparse import csr_matrix,coo_matrix
out = coo_matrix( (phase_space.ravel(), (u_x.ravel(), u_y.ravel())), shape = (M,N))
</code></pre>
<p>输出将是一个稀疏矩阵。要转换为密集型,请使用<code>out.toarray()</code>。你知道吗</p>