我有一个大的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新手,因此教程也会对我有所帮助。
使用 lil_matrix (列表列表矩阵) 的示例,属于scipy。
基于行的链表矩阵。
它包含一列(
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] []]
sorted_ixs
(sorted_ixs = ixs; sorted_ixs.sort()
),(2)使用zip(sorted_ixs, range(len(sorted_ixs))
生成一个匹配索引与“挤压索引”的一对列表,(3)将该列表用作从旧索引到新索引的“翻译表”。 - Michał Marczykfrom 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
>>> 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)]