You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在graph_tool中映射未过滤图与过滤图的顶点索引?

在graph_tool过滤图中获取顶点的局部索引

你遇到的问题是graph_tool的默认vertex_index属性继承自原图,它存储的是顶点在原图中的索引,而非过滤图(GraphView)中的局部索引。所以即使在过滤图中调用vertex_index,返回的依然是该顶点在原图中的编号,这就是为什么你得到的结果是6而不是预期的2。

方法1:建立原图索引到过滤图局部索引的映射

利用fg.get_vertices()返回的数组(该数组按过滤图中顶点的顺序存储原图索引),直接构建映射关系:

import graph_tool as gt
import numpy as np

g = gt.Graph([(1,2),(3,4),(5,6)])
filt = np.array([False, False,False,False,True,True,True])
fg = gt.GraphView(g,vfilt=filt)

# 构建映射字典
orig_to_local = {v: idx for idx, v in enumerate(fg.get_vertices())}
print(orig_to_local[6])  # 输出:2

方法2:为过滤图创建局部索引属性

如果需要频繁查询,可以给过滤图添加一个专门的顶点属性来存储局部索引:

# 创建局部索引属性
local_idx = fg.new_vertex_property("int")
for idx, v in enumerate(fg.vertices()):
    local_idx[v] = idx

# 查询顶点6的局部索引
print(local_idx[fg.vertex(6)])  # 输出:2

类比numpy数组的处理逻辑

在numpy中,假设你有原数组arr和过滤掩码filt,过滤后的数组是filtered_arr = arr[filt]。要找原数组中元素x在过滤后数组中的位置,逻辑是:

  1. 获取过滤后元素的原图索引:filtered_orig_indices = np.where(filt)[0]
  2. 找到x在该数组中的位置:local_idx = np.where(filtered_orig_indices == x)[0][0]

对应到graph_tool场景,fg.get_vertices()等价于filtered_orig_indices,因此可以直接用numpy方式查询:

filtered_orig_indices = fg.get_vertices()
local_idx = np.where(filtered_orig_indices == 6)[0][0]
print(local_idx)  # 输出:2

内容的提问来源于stack exchange,提问作者Joseph Summerhays

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:12:46