我有一个表示图形邻接矩阵的 CSV 文件。但是,该文件的第一行是节点的标签,第一列也是节点的标签。如何将此文件读入 networkx
图形对象?有没有一种简洁的 pythonic 方法可以做到这一点而无需四处乱窜?
到目前为止我的试用:
x = np.loadtxt('file.mtx', delimiter='\t', dtype=np.str)
row_headers = x[0,:]
col_headers = x[:,0]
A = x[1:, 1:]
A = np.array(A, dtype='int')
但这当然不能解决问题,因为我需要在图形创建中为节点添加标签。
数据示例:
Attribute,A,B,C
A,0,1,1
B,1,0,0
C,1,0,0
制表符是分隔符,而不是逗号。
最佳答案
您可以将数据读入结构化数组。标签可以从x.dtype.names
获取,然后可以使用nx.from_numpy_matrix
生成networkx图:
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
# read the first line to determine the number of columns
with open('file.mtx', 'rb') as f:
ncols = len(next(f).split('\t'))
x = np.genfromtxt('file.mtx', delimiter='\t', dtype=None, names=True,
usecols=range(1,ncols) # skip the first column
)
labels = x.dtype.names
# y is a view of x, so it will not require much additional memory
y = x.view(dtype=('int', len(x.dtype)))
G = nx.from_numpy_matrix(y)
G = nx.relabel_nodes(G, dict(zip(range(ncols-1), labels)))
print(G.edges(data=True))
# [('A', 'C', {'weight': 1}), ('A', 'B', {'weight': 1})]
nx.from_numpy_matrix
有一个 create_using
参数,您可以使用它来指定您希望创建的 networkx 图的类型。例如,
G = nx.from_numpy_matrix(y, create_using=nx.DiGraph())
使 G
成为 DiGraph
。
关于python - 从带有行和列标题的 csv 文件中读取 networkx 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24755927/