我有一个大的 csv 文件,其中列出了图中节点之间的连接。例子:
0001,95784
0001,98743
0002,00082
0002,00091
所以这意味着节点 id 0001 连接到节点 95784 和 98743 等等。我需要将其读入 numpy 中的稀疏矩阵。我怎样才能做到这一点?我是 python 新手,所以这方面的教程也会有所帮助。
我有一个大的 csv 文件,其中列出了图中节点之间的连接。例子:
0001,95784
0001,98743
0002,00082
0002,00091
所以这意味着节点 id 0001 连接到节点 95784 和 98743 等等。我需要将其读入 numpy 中的稀疏矩阵。我怎样才能做到这一点?我是 python 新手,所以这方面的教程也会有所帮助。
使用scipy 的lil_matrix(列表矩阵列表)的示例。
基于行的链表矩阵。
这包含一个行列表 (
self.rows
),每行都是非零元素的列索引的排序列表。它还包含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
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
输出:
[[32] [21, 23, 32] [23, 53, 82] [82] [46] [75] [] [86] [28] []]
如果你想要一个邻接矩阵,你可以这样做:
from scipy.sparse import *
from scipy import *
from numpy import *
import csv
S = dok_matrix((10000,10000), dtype=bool)
f = open("your_file_name")
reader = csv.reader(f)
for line in reader:
S[int(line[0]),int(line[1])] = True
您可能还对Networkx感兴趣,这是一个纯 Python 网络/图形包。
从网站:
NetworkX 是一个 Python 包,用于创建、操作和研究复杂网络的结构、动力学和功能。
>>> import networkx as nx
>>> G=nx.Graph()
>>> G.add_edge(1,2)
>>> G.add_node("spam")
>>> print G.nodes()
[1, 2, 'spam']
>>> print G.edges()
[(1, 2)]