您的數據看起來像一個列表的列表:
In [168]: ll = [[196, 242, 3],
...: [186, 302, 3],
...: [22, 377, 1],
...: [196, 377, 3]]
使從它的陣列 - 爲了方便起見,在下面的操作
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]])
移位索引列0基(可選)
In [172]: A[:,:2] -= 1
有了這個它是快速和容易使用定義一個稀疏矩陣coo
(或csr
)格式的(data, (rows, cols))
。迭代的方法dok
有效,但速度更快。
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
M.A
從這個稀疏矩陣創建一個密集數組。一些代碼,特別是sckit-learn
包中的代碼可以直接使用稀疏矩陣。
創造密集排列的直接方式是:
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
我認爲不是每個組合出現,因此搜索稀疏矩陣... –