在使用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 : dictionary10 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 Examples17 --------18 >>> G=nx.path_graph(3) # nodes 0-1-219 >>> 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..2525 >>> mapping=dict(zip(G.nodes(),"abcdefghijklmnopqrstuvwxyz"))26 >>> H=nx.relabel_nodes(G,mapping) # nodes a..z27 >>> mapping=dict(zip(G.nodes(),range(1,27)))28 >>> G1=nx.relabel_nodes(G,mapping) # nodes 1..2629 30 Partial in-place mapping:31 32 >>> G=nx.path_graph(3) # nodes 0-1-233 >>> 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**244 >>> H=nx.relabel_nodes(G,mapping)45 >>> print(H.nodes())46 [0, 1, 4]47 48 Notes49 -----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 Also57 --------58 convert_node_labels_to_integers59 """60 # you can pass a function f(old_label)->new_label61 # but we'll just make a dictionary here regardless62 if not hasattr(mapping,"__getitem__"):63 m = dict((n, mapping(n)) for n in G)64 else:65 m = mapping66 if copy:67 return _relabel_copy(G, m)68 else:69 return _relabel_inplace(G, m)