NetworkX 是用于创建、操作复杂图数据结构的 Python 包。
安装:
pip install networkx
1. 增删节点和边
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.add_nodes_from([2, 3])
G.remove_node(1)
G.remove_nodes_from([2, 3])
G.add_edge(1, 2)
G.add_edges_from([(1, 3), (2, 3)])
G.remove_edge(1, 2)
G.remove_edges_from([(1, 3), (2, 3)])
n_nodes = G.number_of_nodes()
n_edges = G.number_of_edges()
图的节点甚至可以是另一个图:
G1 = nx.Graph()
G2 = nx.Graph()
G.add_nodes_from([G1, G2])
G.add_edge(G1, G2)
2. 文件操作
(1)边列表格式
在边列表文件中,每一行表示一条边(以及可选的属性):
1 2
1 3
2 3
nx.write_edgelist(G, 'edgelist.txt')
G = nx.read_edgelist('edgelist.txt')
(2)gml格式
gml 格式如下:
graph
[
directed 0
node
[
id 0
label "BrighamYoung"
value 7
]
node
[
id 1
label "FloridaState"
value 0
]
...
edge
[
source 1
target 0
]
...
nx.write_gml(G, 'football.gml')
G = nx.read_gml('football.gml', label='id')
3. 获取邻接矩阵
G: nx.Graph = nx.read_edgelist('../data/karate.txt')
A = nx.adj_matrix(G).todense()
print(A)
[[0 1 1 ... 0 0 0]
...
[0 0 0 ... 0 1 0]]
4. 节点和边属性
属性可自定义。
(1)节点属性
G.add_node(1, color="red")
G.add_nodes_from([(2, {"color": "green"}), (3, {"color": "blue"})])
attr = G.nodes[1]
G.nodes[1]['color'] = 'black'
(2)边属性
G.add_edge(1, 2, weight=4.7)
G.add_edges_from([(1, 3, {'weight': 2.3}), (2, 3, {'weight': 6.5})])
attr = G[1][2]
G[1][2]['weight'] = 4.8
5. 遍历节点
(1)遍历节点、节点属性
G = nx.read_gml('../data/football.gml', label='id')
for node in G.nodes():
print(f"{node}: {G.nodes[node]}")
0: {'label': 'BrighamYoung', 'value': 7}
1: {'label': 'FloridaState', 'value': 0}
...
或:
G = nx.read_gml('../data/football.gml', label='id')
for node, attr in G.nodes(data='label'):
print(f'{node}: {attr}')
0: BrighamYoung
1: FloridaState
...
(2)遍历节点、邻居、连边属性
for node, neighs in G.adj.items():
for neigh, edge_attr in neighs.items():
print(f"({node}, {neigh}, {edge_attr})")
(1, 2, {'weight': 4.7})
(1, 3, {'weight': 2.3})
(2, 1, {'weight': 4.7})
(2, 3, {'weight': 6.5})
(3, 1, {'weight': 2.3})
(3, 2, {'weight': 6.5})
6. 遍历边
(1)遍历边
G: nx.Graph = nx.read_gml('../data/football.gml', label='id')
for edge in G.edges():
print(edge)
(0, 1)
(0, 4)
...
(2)遍历边、边属性
G = nx.Graph()
G.add_node(1, color="red")
G.add_nodes_from([(2, {"color": "green"}), (3, {"color": "blue"})])
G.add_edge(1, 2, weight=4.7)
G.add_edges_from([(1, 3, {'weight': 2.3}), (2, 3, {'weight': 6.5})])
for u, v in G.edges():
print(f'edge: ({u}, {v}), attrs: {G[u][v]}')
edge: (1, 2), attrs: {'weight': 4.7}
edge: (1, 3), attrs: {'weight': 2.3}
edge: (2, 3), attrs: {'weight': 6.5}
或者:
for edge, attrs in G.edges().items():
print(f'edge: {edge}, attrs: {attrs}')
7. 可视化
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from([1, 2, 3])
G.add_edges_from([(1, 2), (1, 3), (2, 3)])
partition = {
1: 0,
2: 1,
3: 0,
}
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, partition.keys(), node_size=300,
alpha=0.3, node_color=list(partition.values()))
nx.draw_networkx_edges(G, pos, alpha=0.5)
nx.draw_networkx_labels(G, pos)
plt.show()
|