跳至内容
Networkx.Graph类

Networkx.Graph类

networkx.Graph 类常见方法和属性

目录


1. 初始化图

1
2
import networkx as nx
G = nx.Graph()  # 创建空的无向图

2. 添加节点

1
2
3
4
5
# 添加单个节点(带属性)
G.add_node(1, color='red', size=10)

# 批量添加节点  节点2、3共用属性
G.add_nodes_from([2, 3], category='A') 

3. 添加边

1
2
3
4
5
6
7
8
# 添加单条边(带权重)
G.add_edge(1, 2, weight=4.7)

# 批量添加边
G.add_edges_from([(1, 3), (2, 3)], type='friendship')

# 批量添加带权重的边
G.add_weighted_edges_from([(1, 2, 0.5), (2, 3, 0.8)])

4. 删除节点/边

1
2
3
4
5
6
7
# 删除节点
G.remove_node(1)
G.remove_nodes_from([2, 3])

# 删除边
G.remove_edge(1, 2)
G.remove_edges_from([(1, 2), (2, 3)])

5. 检查存在性

1
2
G.has_node(1)   # 返回布尔值
G.has_edge(1,2) # 返回布尔值

6. 基本属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# 节点和边视图
list(G.nodes)         # [1, 2, 3]
list(G.edges(data='weight'))  # 边及属性

# 邻接字典
G.adj[1]  # 输出: {2: {'weight': 0.5}}

# 全局属性
G.graph['name'] = 'My Graph'

# 统计方法
G.number_of_nodes()  # 节点总数
G.number_of_edges()  # 边总数

7. 节点与边的属性

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 节点属性操作,先要保证 1 结点存在
G.nodes[1]['color'] = 'blue'
G.nodes.add(2, 'color' = 'blue')

color = G.nodes[1].get('color', 'default')
color = G.nodes.get(1, 'color', 'default')

# 边属性操作
G.edges[1, 2]['weight'] = 5.0
weight = G.edges[1, 2].get('weight', 1.0)

注意点:

  1. 语法等效性:属性名 color(关键字参数)和 'color'(字典键)本质是同一个属性。

  2. 安全操作:用 G.nodes.get(2, {}) 可避免异常。

1
2
3
4
5
6
7
8
9
import networkx as nx

# 创建图并添加节点(两种等效方式)
G = nx.Graph()
G.add_node(2, color='blue')       

# 访问属性(需确保节点和属性名正确),用'color'访问
print(G.nodes[2]['color'])   	    # 'blue'
print(G.nodes.get(2,'color')        # 'blue'

8. 图的操作

1
2
3
G.clear()       # 清空图(保留属性)
G.copy()        # 深拷贝图
subG = G.subgraph([1, 2])  # 生成子图

9. 节点邻居与度数

1
2
list(G.neighbors(1))  # 返回邻居列表
G.degree(1)           # 返回节点度数

10. 示例代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import networkx as nx

# 创建图
G = nx.Graph(name="示例图")
G.add_nodes_from([1, 2, 3], category='sample')
G.add_edges_from([(1, 2), (2, 3)], weight=1.0)

# 设置属性
G.nodes[1]['color'] = 'red'
G.edges[1, 2]['weight'] = 2.5

# 输出信息
print("节点列表:", list(G.nodes))
print("边列表:", list(G.edges(data=True)))
print("节点1的邻居:", list(G.neighbors(1)))
print("节点1的度数:", G.degree(1))

注意事项

  • 边操作会自动添加不存在的节点
  • 节点支持任意可哈希对象(如元组、字符串)
  • 批量操作比逐条操作更高效
最后更新于