Python Networkx - 删除特定节点和相关边

Python Networkx - Remove specific node and related edges

我有一个包含节点和边的 graphml 文件。我正在尝试删除 data['zone'] != 'gold' 所在的每个节点。 这是我的图表的样子:

<?xml version='1.0' encoding='utf-8'?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <key id="d4" for="node" attr.name="source" attr.type="string" />
  <key id="d3" for="node" attr.name="use_case" attr.type="string" />
  <key id="d2" for="node" attr.name="kind" attr.type="string" />
  <key id="d1" for="node" attr.name="zone" attr.type="string" />
  <key id="d0" for="node" attr.name="table" attr.type="string" />
  <graph edgedefault="directed">
    <node id="097373">
      <data key="d0">valid_outer_cases_not_attached_to_pallet</data>
      <data key="d1">gold</data>
      <data key="d2">adhoc</data>
      <data key="d3">low</data>
    </node>
    <node id="36372">
      <data key="d0">kpis</data>
      <data key="d1">gold</data>
      <data key="d2">adhoc</data>
      <data key="d3">low</data>
    </node>

parser.py

import networkx as nx
import matplotlib.pyplot as plt


input_graph = nx.read_graphml("graph.graphml")

for node, data in input_graph.nodes(data=True):
    if data['zone'] != 'gold':
        input_graph.remove_node(node)

错误日志: RuntimeError: dictionary changed size during iteration

您可以标记要移除的节点,然后移除它们:

to_remove = []
for node, data in input_graph.nodes(data=True):
    if data['zone'] != 'gold':
        to_remove.append(node)

input_graph.remove_nodes_from(to_remove)

使用理解删除不需要的节点:

input_graph = nx.read_graphml("graph.graphml")
input_graph.remove_nodes_from([n for n, d in G.nodes(data=True) 
                                   if d.get('zone') != 'gold'])

如果 zone 属性不存在,请使用 dict.get 以避免引发异常。