numpy scipy python从cs导入稀疏矩阵

2024-04-25 17:52:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.csv文件格式如下:

id_A,id_B 2135,1 2303,1 6292,1

大约180k的条目表示稀疏矩阵中矩阵的位置为1(另一个值为0)。 我想知道是否有一种方法可以用numpy或scipy在python中导入它。在

谢谢


我试过这样的方法,似乎奏效了

with open('icm.csv', 'rt') as f:
    reader = csv.reader(f)
    list = list(reader)
row = [] #i[:] the row indices of the matrix entries
coloumn = [] #[:] the column indices of the matrix entries
data=[] #data[:] the entries of the matrix, in any order
for i in range(1,len(list)):
    row.append(int(list[i][0]))
    coloumn.append(int(list[i][1]))
    data.append(1)
matrix = coo_matrix((data, (coloumn, row)))

Tags: ofcsvthe方法iddata矩阵matrix
1条回答
网友
1楼 · 发布于 2024-04-25 17:52:26

从您的示例中创建一个示例“文件”:

In [47]: txt=b"""id_A,id_B
 2135,1
 2303,1
 6292,1"""

genfromtxt加载它;结果是一个有2个字段('columns')的结构化数组:

^{pr2}$

从该数据创建coo格式矩阵:

In [51]: from scipy import sparse
In [52]: M=sparse.coo_matrix((np.ones_like(data['id_A']),
             (data['id_A'],data['id_B'])))
In [53]: M
Out[53]: 
<6293x2 sparse matrix of type '<class 'numpy.int32'>'
    with 3 stored elements in COOrdinate format>
In [54]: M.row
Out[54]: array([2135, 2303, 6292], dtype=int32)
In [55]: M.col
Out[55]: array([1, 1, 1], dtype=int32)
In [56]: M.data
Out[56]: array([1, 1, 1])

相关问题 更多 >