您可以将数据读入结构化数组.可以从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 Graph的类型.例如,
G = nx.from_numpy_matrix(y, create_using=nx.DiGraph())
使G成为DiGraph.