使用pyvis可视化networkx图时出现category KeyError如何解决?
问题原因
你触发KeyError: 'category'的核心原因是图中存在部分节点没有被赋值category属性:nx.from_pandas_edgelist会自动为边表中出现的所有user_id创建节点,若你的df_edges中存在未出现在df_nodes里的user_id,这些自动生成的节点不会被nx.set_node_attributes赋值属性,遍历访问不存在的category字段时就会触发报错。你在函数外测试时只测试了存在属性的节点,所以未触发问题。
排查步骤
先运行以下代码确认问题根源:
# 检查全图所有节点是否存在category属性 missing_attr_nodes = [n for n in G.nodes if 'category' not in G.nodes[n]] print(f"缺少category属性的节点列表:{missing_attr_nodes}") print(f"缺失属性节点数量:{len(missing_attr_nodes)}")
如果输出存在缺失属性的节点,即可确认是上述原因。
修复方案
方案1:前置过滤边表,保证所有边的两端节点都存在于节点表中,从根源避免无属性节点生成
# 提前获取所有合法节点集合 valid_user_ids = set(df_nodes['user_id']) # 过滤边表,仅保留两端都是合法节点的边 df_edges_filtered = df_edges[ df_edges['user_id_x'].isin(valid_user_ids) & df_edges['user_id_y'].isin(valid_user_ids) ] # 用过滤后的边表建图 G = nx.from_pandas_edgelist(df_edges_filtered, 'user_id_x', 'user_id_y')
方案2:遍历节点时增加属性存在性判断,避免报错
for n in SG: # 属性缺失时设置默认样式 if 'category' not in SG.nodes[n] or 'status' not in SG.nodes[n]: color = 'gray' shape = 'circle' elif SG.nodes[n]['category'] == 'cust' and SG.nodes[n]['status'] == 'ACTIVE': color = 'green' shape = 'square' elif SG.nodes[n]['category'] == 'cust' and SG.nodes[n]['status'] == 'CLOSED': color = 'red' shape = 'square' elif SG.nodes[n]['category'] == 'app': color = 'blue' shape = 'triangle' N.add_node(n, label=n, color=color, shape=shape)
注:你原有代码中条件判断存在逻辑瑕疵,第一个if后未加el,会导致cust类型节点同时触发两个判断,上述修复后逻辑更严谨。
内容的提问来源于stack exchange,提问作者AAA
相关产品推荐
相关产品推荐

