scipy 稀疏矩阵访问列和行索引值
scipy sparse matrix access column and row index value
我有一个 csr matrix
,其中所有值都是 1
。我想访问打印矩阵时看到的元组中的第一个和第二个元素。第一个是用户,第二个是项目。
我不明白如何轻松获得这些元素。
(0, 1) 1
(1, 0) 1
(2, 2) 1
(3, 1) 1
(3, 2) 1
(4, 3) 1
(5, 2) 1
matrix = [[0,1,0,0],
[1,0,0,0],
[0,0,1,0],
[0, 1, 1, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]]
预期结果:
0: 1
1: 0
2: 2
3: 1,2
4: 3
5: 2
csr_matrix
的 nonzero
方法似乎就是您要找的。
来自 scipy documentation:
csr_matrix.nonzero()
Returns a tuple of arrays (row,col) containing the indices of the
non-zero elements of the matrix.
因此,为了提取您想要的信息,我建议创建一个字典,它可以让您轻松地继续使用数据。例如,可以这样做:
res_dict = {key: [] for key in matrix.nonzero()[0]}
for row, col in zip(*matrix.nonzero()):
res_dict[row].append(col)
给定矩阵的输出如下:
{0: [1], 1: [0], 2: [2], 3: [1, 2], 4: [3], 5: [2]}
In [60]: from scipy import sparse
In [61]: M = sparse.csr_matrix([[0,1,0,0],
...: [1,0,0,0],
...: [0,0,1,0],
...: [0, 1, 1, 0],
...: [0, 0, 0, 1],
...: [0, 0, 1, 0]] )
In [62]: M
Out[62]:
<6x4 sparse matrix of type '<class 'numpy.int64'>'
with 7 stored elements in Compressed Sparse Row format>
In [63]: print(M)
(0, 1) 1
(1, 0) 1
(2, 2) 1
(3, 1) 1
(3, 2) 1
(4, 3) 1
(5, 2) 1
lil
格式的 rows
属性是一个对象 dtype 列表数组 - 矩阵的每一行都有一个索引列表:
In [64]: M.tolil().rows
Out[64]:
array([list([1]), list([0]), list([2]), list([1, 2]), list([3]),
list([2])], dtype=object)
M.nonzero
returns row
和 col
属性的 coo
格式:
In [66]: M.tocoo().col
Out[66]: array([1, 0, 2, 1, 2, 3, 2], dtype=int32)
In [67]: M.tocoo().row
Out[67]: array([0, 1, 2, 3, 3, 4, 5], dtype=int32)
我有一个 csr matrix
,其中所有值都是 1
。我想访问打印矩阵时看到的元组中的第一个和第二个元素。第一个是用户,第二个是项目。
我不明白如何轻松获得这些元素。
(0, 1) 1
(1, 0) 1
(2, 2) 1
(3, 1) 1
(3, 2) 1
(4, 3) 1
(5, 2) 1
matrix = [[0,1,0,0],
[1,0,0,0],
[0,0,1,0],
[0, 1, 1, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]]
预期结果:
0: 1
1: 0
2: 2
3: 1,2
4: 3
5: 2
csr_matrix
的 nonzero
方法似乎就是您要找的。
来自 scipy documentation:
csr_matrix.nonzero()
Returns a tuple of arrays (row,col) containing the indices of the non-zero elements of the matrix.
因此,为了提取您想要的信息,我建议创建一个字典,它可以让您轻松地继续使用数据。例如,可以这样做:
res_dict = {key: [] for key in matrix.nonzero()[0]}
for row, col in zip(*matrix.nonzero()):
res_dict[row].append(col)
给定矩阵的输出如下:
{0: [1], 1: [0], 2: [2], 3: [1, 2], 4: [3], 5: [2]}
In [60]: from scipy import sparse
In [61]: M = sparse.csr_matrix([[0,1,0,0],
...: [1,0,0,0],
...: [0,0,1,0],
...: [0, 1, 1, 0],
...: [0, 0, 0, 1],
...: [0, 0, 1, 0]] )
In [62]: M
Out[62]:
<6x4 sparse matrix of type '<class 'numpy.int64'>'
with 7 stored elements in Compressed Sparse Row format>
In [63]: print(M)
(0, 1) 1
(1, 0) 1
(2, 2) 1
(3, 1) 1
(3, 2) 1
(4, 3) 1
(5, 2) 1
lil
格式的 rows
属性是一个对象 dtype 列表数组 - 矩阵的每一行都有一个索引列表:
In [64]: M.tolil().rows
Out[64]:
array([list([1]), list([0]), list([2]), list([1, 2]), list([3]),
list([2])], dtype=object)
M.nonzero
returns row
和 col
属性的 coo
格式:
In [66]: M.tocoo().col
Out[66]: array([1, 0, 2, 1, 2, 3, 2], dtype=int32)
In [67]: M.tocoo().row
Out[67]: array([0, 1, 2, 3, 3, 4, 5], dtype=int32)