<p>您的数据看起来像一个列表列表:</p>
<pre><code>In [168]: ll = [[196, 242, 3],
...: [186, 302, 3],
...: [22, 377, 1],
...: [196, 377, 3]]
</code></pre>
<p>从中生成一个数组-以便于执行以下操作</p>
<pre><code>In [169]: A = np.array(ll)
In [170]: ll
Out[170]: [[196, 242, 3], [186, 302, 3], [22, 377, 1], [196, 377, 3]]
In [171]: A
Out[171]:
array([[196, 242, 3],
[186, 302, 3],
[ 22, 377, 1],
[196, 377, 3]])
</code></pre>
<p>将索引列移到0基(可选)</p>
<pre><code>In [172]: A[:,:2] -= 1
</code></pre>
<p>使用这种方法,可以使用<code>coo</code>(或<code>csr</code>)格式,即<code>(data, (rows, cols))</code>,快速而简单地定义稀疏矩阵。迭代<code>dok</code>方法是可行的,但速度更快。你知道吗</p>
<pre><code>In [174]: from scipy import sparse
In [175]: M = sparse.csr_matrix((A[:,2],(A[:,0], A[:,1])), shape=(942,1681))
In [176]: M
Out[176]:
<942x1681 sparse matrix of type '<class 'numpy.int32'>'
with 4 stored elements in Compressed Sparse Row format>
In [177]: print(M)
(21, 376) 1
(185, 301) 3
(195, 241) 3
(195, 376) 3
</code></pre>
<p><code>M.A</code>从这个稀疏矩阵创建一个密集数组。一些代码,尤其是<code>sckit-learn</code>包中的代码可以直接使用稀疏矩阵。你知道吗</p>
<p>创建密集阵列的直接方法是:</p>
<pre><code>In [183]: N = np.zeros((942,1681),int)
In [184]: N[A[:,0],A[:,1]]= A[:,2]
In [185]: N.shape
Out[185]: (942, 1681)
In [186]: M.A.shape
Out[186]: (942, 1681)
In [187]: np.allclose(N, M.A) # it matches the sparse version
Out[187]: True
</code></pre>