csv到python中的稀疏矩阵 [英] csv to sparse matrix in python
问题描述
0001,95784
0001,98743
0002,00082
0002,00091
所以这意味着节点id 0001连接到节点95784和98743,依此类推。
我需要把它读成一个稀疏矩阵,以numpy为单位。我该怎么办?
我是python的新手,所以教程也将有所帮助。
使用 lil_matrix (列表矩阵列表)的scipy。
基于行的链表列表矩阵。
这包含一个列表(
self)行
)行,每个行都是非零元素的列索引的排序列表。它还包含这些元素列表的列表(self.data
)。
$ cat 1938894-simplified.csv
0,32
1,21
1,23
1,32
2,23
2,53
2,82
3,82
4,46
5,75
7,86
8 ,28
代码:
#/ usr / bin / env python
import csv
从scipy import sparse
rows,columns = 10,100
matrix = sparse.lil_matrix((rows,columns))
csvreader = csv.reader(open('1938894-simplified.csv'))
在csvreader中的行:
row,column = map(int,line)
matrix.data [row] .append(column)
print matrix.data
输出:
[[32] [ 21,23,32] [23,53,82] [82] [46] [75] [] [86] [28] []]
I have a big csv file which lists connections between nodes in a graph. example:
0001,95784
0001,98743
0002,00082
0002,00091
So this means that node id 0001 is connected to node 95784 and 98743 and so on. I need to read this into a sparse matrix in numpy. How can i do this? I am new to python so tutorials on this would also help.
Example using lil_matrix (list of list matrix) of scipy.
Row-based linked list matrix.
This contains a list (
self.rows
) of rows, each of which is a sorted list of column indices of non-zero elements. It also contains a list (self.data
) of lists of these elements.
$ cat 1938894-simplified.csv
0,32
1,21
1,23
1,32
2,23
2,53
2,82
3,82
4,46
5,75
7,86
8,28
Code:
#!/usr/bin/env python
import csv
from scipy import sparse
rows, columns = 10, 100
matrix = sparse.lil_matrix( (rows, columns) )
csvreader = csv.reader(open('1938894-simplified.csv'))
for line in csvreader:
row, column = map(int, line)
matrix.data[row].append(column)
print matrix.data
Output:
[[32] [21, 23, 32] [23, 53, 82] [82] [46] [75] [] [86] [28] []]
这篇关于csv到python中的稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!