我是python和networkx的新手。 如何通过导入csv格式的权重邻接矩阵来创建定向和加权网络(参见下面的2 * 2示例)?
3.4, 1.2, 0.8, 1.3,提前致谢。
I am new to python and networkx. How can I create a directed and weighted network by importing a weights adjacency matrix in csv format (see below for a 2*2 example)?
3.4, 1.2, 0.8, 1.3,Thanks in advance.
最满意答案
至少有两个选项:您可以使用numpy.loadtxt这样的文件直接读入numpy数组。 也许这就是您所需要的全部,因为您可能希望使用矩阵对其执行线性代数运算。
如果您需要定向网络,则只需使用networkx.from_numpy_matrix从中初始化图形:
adj_mat = numpy.loadtxt(filename) net = networkx.from_numpy_matrix(adj_mat, create_using=networkx.DiGraph()) net.edges(data=True) [(0, 0, {'weight': 3.4}), (0, 1, {'weight': 1.2}), (1, 0, {'weight': 0.8}), (1, 1, {'weight': 1.3})]There are at least two options: You can read such a file directly into a numpy array using numpy.loadtxt. Maybe that is all you need since you might want to use the matrix to perform linear algebra operations on it.
If you need a directed network you can then simply initialize a graph from it with networkx.from_numpy_matrix:
adj_mat = numpy.loadtxt(filename) net = networkx.from_numpy_matrix(adj_mat, create_using=networkx.DiGraph()) net.edges(data=True) [(0, 0, {'weight': 3.4}), (0, 1, {'weight': 1.2}), (1, 0, {'weight': 0.8}), (1, 1, {'weight': 1.3})]更多推荐
发布评论