樣品稀疏矩陣:
In [363]: A=sparse.csr_matrix(np.arange(12).reshape(3,4))
其顯示爲緻密的(常規numpy的)陣列(例如A.toarray()
)
In [364]: A.A
Out[364]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]], dtype=int32)
及其repr
顯示
In [365]: A
Out[365]:
<3x4 sparse matrix of type '<class 'numpy.int32'>'
with 11 stored elements in Compressed Sparse Row format>
及其str()
顯示器(你看到了什麼)
In [366]: print(A)
(0, 1) 1
(0, 2) 2
(0, 3) 3
(1, 0) 4
(1, 1) 5
(1, 2) 6
(1, 3) 7
(2, 0) 8
(2, 1) 9
(2, 2) 10
(2, 3) 11
A.data
是它的數據屬性的值。你可以用nonzero
獲取座標:
In [368]: A.nonzero()
Out[368]:
(array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], dtype=int32),
array([1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], dtype=int32))
或轉換csr
到coo
格式,並得到所有3個數組:
In [369]: Ac=A.tocoo()
In [370]: Ac.data
Out[370]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], dtype=int32)
In [371]: Ac.row
Out[371]: array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], dtype=int32)
In [372]: Ac.col
Out[372]: array([1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], dtype=int32)
你可以把它們變成一個3列陣列:
In [373]: np.column_stack((Ac.col, Ac.row, Ac.data))
Out[373]:
array([[ 1, 0, 1],
[ 2, 0, 2],
[ 3, 0, 3],
[ 0, 1, 4],
[ 1, 1, 5],
[ 2, 1, 6],
[ 3, 1, 7],
[ 0, 2, 8],
[ 1, 2, 9],
[ 2, 2, 10],
[ 3, 2, 11]], dtype=int32)
除非你的數據是浮動的,那麼這將成爲所有浮動。它不能混合整數和浮點數。
您可以將它們組裝到一個帶有2個int字段和一個float字段的結構化數組中。如果需要,我可以詳細說明。
但是您提到的數據框表明您熟悉pandas
- 如果是這樣的話,您可能可以從此處獲取它。
非常感謝..它的工作! – user3775161