如何重命名图中的所有节点?

How to rename all nodes in a graph?

我正在使用 NetworkX 读取 GraphML 文件。我的 GraphML 图中有超过 1000 个节点,我试图根据某些条件更改每个节点的 ID,例如:

if "gold" in node.id: 
    node.id = "hello_world"

这是我的输入图示例:

graph.graphml

<node id="gold_core.pc_loc_country_mapping"> 
  <data key="d0">pc_loc_country_mapping</data>
  <data key="d1">gold</data>
  <data key="d2">core</data>
</node>
<node id="gold_core.products">
  <data key="d0">products</data>
  <data key="d1">gold</data>
  <data key="d2">core</data>
</node>

read_graph.py

networkx_graph = nx.read_graphml(GRAPH_ML_PATH)    
nodes_to_remove = []
    for node, data in networkx_graph.nodes(data=True):
        if data['zone'] != GOLD_NODES_ID and networkx_graph.degree(node) < 1:
            nodes_to_remove.append(node)
    networkx_graph.remove_nodes_from(nodes_to_remove)
    return networkx_graph

如果你想改变节点ids,你可以使用函数relabel_nodes:

renaming_mapping = {}
for node, data in graph.nodes(data=True):
    if condition: 
        renaming_mapping[node] = "new individual name"
graph_with_new_names = nx.relabel_nodes(graph, renaming_mapping)