csv 到 python 中的稀疏矩阵

问题描述 投票:0回答:3

我有一个很大的 csv 文件,其中列出了图中节点之间的连接。例子:

0001,95784
0001,98743
0002,00082
0002,00091

所以这意味着节点 id 0001 连接到节点 95784 和 98743 等等。 我需要将其读入 numpy 中的稀疏矩阵。我怎样才能做到这一点? 我是 python 的新手,所以这方面的教程也会有所帮助。

python data-structures sparse-matrix
3个回答
12
投票

使用 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] []]

2
投票

如果你想要一个邻接矩阵,你可以这样做:

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

2
投票

您可能也对 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)]
© www.soinside.com 2019 - 2024. All rights reserved.