• AttributeError: 'str' object has no attribute 'copy'


    在使用Python Networkx 中的relabel_nodes函数时,出现:

    AttributeError: 'str' object has no attribute 'copy'

    找了半天也没发现错误出现在哪里,通过比较发现:

    如果在定义图的类型时候使用G=nx.MultiDiGraph()就会出现这个错误,改为G=nx.Graph()错误消失。

    目测是relabel_nodes函数不支持MultiDiGraph。

    附:

     1 def relabel_nodes(G, mapping, copy=True):
     2     """Relabel the nodes of the graph G.
     3 
     4     Parameters
     5     ----------
     6     G : graph
     7        A NetworkX graph
     8 
     9     mapping : dictionary
    10        A dictionary with the old labels as keys and new labels as values.
    11        A partial mapping is allowed.
    12 
    13     copy : bool (optional, default=True)
    14        If True return a copy, or if False relabel the nodes in place.
    15 
    16     Examples
    17     --------
    18     >>> G=nx.path_graph(3)  # nodes 0-1-2
    19     >>> mapping={0:'a',1:'b',2:'c'}
    20     >>> H=nx.relabel_nodes(G,mapping)
    21     >>> print(sorted(H.nodes()))
    22     ['a', 'b', 'c']
    23 
    24     >>> G=nx.path_graph(26) # nodes 0..25
    25     >>> mapping=dict(zip(G.nodes(),"abcdefghijklmnopqrstuvwxyz"))
    26     >>> H=nx.relabel_nodes(G,mapping) # nodes a..z
    27     >>> mapping=dict(zip(G.nodes(),range(1,27)))
    28     >>> G1=nx.relabel_nodes(G,mapping) # nodes 1..26
    29 
    30     Partial in-place mapping:
    31 
    32     >>> G=nx.path_graph(3)  # nodes 0-1-2
    33     >>> mapping={0:'a',1:'b'} # 0->'a' and 1->'b'
    34     >>> G=nx.relabel_nodes(G,mapping, copy=False)
    35 
    36     print(G.nodes())
    37     [2, 'b', 'a']
    38 
    39     Mapping as function:
    40 
    41     >>> G=nx.path_graph(3)
    42     >>> def mapping(x):
    43     ...    return x**2
    44     >>> H=nx.relabel_nodes(G,mapping)
    45     >>> print(H.nodes())
    46     [0, 1, 4]
    47 
    48     Notes
    49     -----
    50     Only the nodes specified in the mapping will be relabeled.
    51 
    52     The keyword setting copy=False modifies the graph in place.
    53     This is not always possible if the mapping is circular.
    54     In that case use copy=True.
    55 
    56     See Also
    57     --------
    58     convert_node_labels_to_integers
    59     """
    60     # you can pass a function f(old_label)->new_label
    61     # but we'll just make a dictionary here regardless
    62     if not hasattr(mapping,"__getitem__"):
    63         m = dict((n, mapping(n)) for n in G)
    64     else:
    65         m = mapping
    66     if copy:
    67         return _relabel_copy(G, m)
    68     else:
    69         return _relabel_inplace(G, m)
  • 相关阅读:
    Android开发学习--RecycleView入门
    Android开发学习--MVP模式入门
    Android开发学习--ViewPager使用入门
    LocalDB
    Asp.Net Mvc5新特性
    Asp.net MVC4 捆绑和压缩
    实施双工通信框架:SignalR
    Razor 语法
    Action Result
    操作Action
  • 原文地址:https://www.cnblogs.com/purple-blog/p/4593786.html
Copyright © 2020-2023  润新知