【问题标题】:remove edges NetworkX删除边缘 NetworkX
【发布时间】:2023-02-25 14:51:34
【问题描述】:

我构建了一个包含以下详细信息的图表。我感到困惑的是,为什么在删除图形的一条边之后,当我尝试打印所有边数据时它仍然存在?我做错什么了吗?

import networkx as nx

G = nx.MultiGraph()
G.add_edge(17, 12, nm=5, asset="a12")
G.add_edge(14, 13, nm=15, asset="a13")
G.add_edge(17, 13, nm=5, asset="a14")
G.add_edge(27, 110, nm=15, asset="a15")
G.add_edge(27, 110, nm=5, asset="a19")
G.add_edge(27, 280, nm=5, asset="a19")

# remove asset a15
for a, b, attributes in G.edges(data=True):
    if attributes["asset"]=="a15": 
        lst=[(a, b)]
G.remove_edges_from(lst)

#print the current edges in the graph
for cc in nx.connected_components(G):
   print("asset", list(nx.get_edge_attributes(G.subgraph(cc), "asset").values()))

输出:

asset ['a12', 'a14', 'a13']
asset ['a19', 'a15']

为什么'a15' 仍然存在?

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    对于 MultiGraph,remove_edges_from(和 remove_edge,仅删除一条边)将删除指定节点之间最近添加的边,除非您通过提供键另行通知。您的代码删除了27110 之间标记为'a19' 的边,因为它是在标记为'a15' 的边之后添加的。 (您仍然会在打印输出中看到 'a19',因为您还将该资产名称赋予了 27280 之间的边缘。)

    您可以通过向 edges 方法提供 keys=True 来获取相关节点的密钥,如下所示:

    for a, b, key, attributes in G.edges(keys=True, data=True):
        if attributes["asset"] == "a15": 
            G.remove_edge(a, b, key)
            break
    

    如果你要删除一条边,你可以使用remove_edge而不是remove_edges_from,并且一旦你这样做了就可以继续break退出循环。

    值得注意的是,add_edge回报新边缘的关键,因此您可以根据需要提前保存它们。这些键应该保持唯一对于任何特定的节点对.

    【讨论】:

      【解决方案2】:

      看起来你有两条边连接两个相同的节点("27" and "110")。您的变量lst 返回元组(27, 110) 并且方法remove_edges_from 删除称为a19 的边以代替a15。另一种方法是添加另一个条件,如下所示:

      for a, b, attributes in G.edges(data=True):
          if attributes["asset"]=="a15" and attributes["nm"]==15 : 
              lst=[(a, b)]
      G.remove_edges_from(lst)
      

      【讨论】:

      • 感谢您的回复。是的,我有两条边连接到相同的节点,这是有意的,我想通过资产删除边,因为它是一个独特的属性。我有很多属性,即资产、纳米、年份、类型等,但不确定这是否是去除边缘的正确方法。我确实尝试了您提供的代码,但它仍在输出资产 a15
      猜你喜欢
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2012-10-24
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      相关资源
      最近更新 更多