【问题标题】:NetworkX remove attributes from a specific nodeNetworkX 从特定节点删除属性
【发布时间】:2018-05-08 13:32:32
【问题描述】:

我在 python 中遇到了 networkX 库的问题。我建立了一个图表 初始化一些节点,带有属性的边。我还开发了一种方法,可以将具有特定值的特定属性动态添加到目标节点。例如:

 def add_tag(self,G,fnode,attr,value):
    for node in G:
        if node == fnode:
           attrs = {fnode: {attr: value}}
           nx.set_node_attributes(G,attrs)

因此如果我们打印目标节点的属性将被更新

        print(Graph.node['h1'])

{'color': u'green'}

        self.add_tag(Graph,'h1','price',40)
        print(Graph.node['h1'])

{'color': u'green', 'price': 40}

我的问题是如何从目标节点中删除现有属性?我找不到任何删除/删除属性的方法。我发现只是 .update 方法并没有帮助。

谢谢

【问题讨论】:

    标签: python networkx


    【解决方案1】:

    属性是python字典,所以你可以使用del来删除它们。

    例如,

    In [1]: import networkx as nx
    
    In [2]: G = nx.Graph()
    
    In [3]: G.add_node(1,color='red')
    
    In [4]: G.node[1]['shape']='pear'
    
    In [5]: list(G.nodes(data=True))
    Out[5]: [(1, {'color': 'red', 'shape': 'pear'})]
    
    In [6]: del G.node[1]['color']
    
    In [7]: list(G.nodes(data=True))
    Out[7]: [(1, {'shape': 'pear'})]
    

    【讨论】:

    • 第 4 行和第 6 行应该是 G.nodes 而不是 G.node(至少对于 networkx 2.4)
    【解决方案2】:

    我想你提出的 del 方法会起作用。 你给了我一个好主意来构建一个这样的 remove_attribute 方法(使用 pop):

     def remove_attribute(self,G,tnode,attr):
        G.node[tnode].pop(attr,None)
    

    其中 tnode 是目标节点,attr 是我们要移除的属性。

    【讨论】:

    • 只是一个愚蠢的问题@Dimitris。我应该如何使用你的功能?如果我写这样的东西:g = g.remove_attribute(tnode='926', attr='bipartite') 它会出现:AttributeError: 'Graph' object has no attribute 'remove_attribute'
    猜你喜欢
    • 2023-02-14
    • 2016-04-23
    • 2018-01-09
    • 2011-04-28
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多