import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
source = [1, 2, 3, 4, 5]
target = [2, 3, 4, 5, 6]
id = [10, 11, 12, 13, 14]
df = pd.DataFrame({'id': id, 'source': source, 'target': target})
print(df)
graph = nx.Graph()
pipe_data_dict = df.to_dict(orient='records')
for pipe in pipe_data_dict:
graph.add_edge(pipe['source'], pipe['target'], gid=pipe['id'])
plt.figure(figsize=(6, 4))
pos = nx.circular_layout(graph)
nx.draw(graph, pos=pos, with_labels=True)
plt.savefig("demo", dpi=1000, bbox_inches='tight')
for source, target in nx.dfs_edges(graph, 2, depth_limit=1):
print("source:", source, "target:", target)
print("id:", graph[source][target]['gid'])
结果
id source target
0 10 1 2
1 11 2 3
2 12 3 4
3 13 4 5
4 14 5 6
source: 2 target: 1
id: 10
source: 2 target: 3
id: 11