我有一个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
答案 0 :(得分:0)
您正在寻找nonzero
的{{1}}方法。
来自scipy documentation:
csr_matrix.nonzero()
返回一个数组(行,列)的元组,其中包含 矩阵的非零元素。
因此,为了提取所需的信息,我建议创建一个字典,该字典可以轻松地使您继续处理数据。例如,可以这样进行:
csr_matrix
给定矩阵的输出如下:
res_dict = {key: [] for key in matrix.nonzero()[0]}
for row, col in zip(*matrix.nonzero()):
res_dict[row].append(col)
答案 1 :(得分:0)
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
rows
格式的lil
属性是列表的对象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
返回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)