csv到python中的稀疏矩阵

2024-04-26 13:09:52 发布

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

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

000195784
000198743
000200082
0002000091号

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


Tags: 文件csvnumpyid示例节点图表教程
3条回答

如果需要邻接矩阵,可以执行以下操作:

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 is a Python package for the creation, manipulation, and study of the structure, dynamics, and functions of complex networks.

>>> 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)]

使用scipy的lil_matrix(列表矩阵列表)的示例。

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

代码:

#!/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] []]

相关问题 更多 >