使用 pandas 将 .csv 文件作为 df 读取可能是最简单的方法,然后执行列表推导以将每一行提取为 networkx 库可读的格式。
以下代码部分改编自:Drawing a network with nodes and edges in Python3
...对圆形布局中的有向图进行修改,节点、边和权重是您的 df 的列
import pandas as pd
import matplotlib.pyplot as plt
import networkx as nx
df = pd.DataFrame({'nodes': [1,2,4,5], 'edges': [2,3,5,6], 'weights': [45,24,98,12]})
# each edge is a tuple of the form (node, edge/node, {'weight': weight})
edges = [(x, y, {'weight': z}) for x, y, z in zip(df['nodes'], df['edges'], df['weights'])]
# a directed graph has arrows pointing to edges
G = nx.DiGraph()
G.add_edges_from(edges)
# create a circular layout
pos = nx.circular_layout(G)
# draw the nodes
nx.draw_networkx_nodes(G,pos, node_size=300)
# draw the labels
nx.draw_networkx_labels(G,pos, font_size=15,font_family='sans-serif')
# draw the edges
nx.draw_networkx_edges(G,pos, edgelist=edges, arrowstyle = '-|>', width=1)
# add weights
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos, edge_labels=labels)
plt.show()