给定在NetworkX中创建的任何图形G,我希望能够在创建图形之后为G.edges()分配一些权重。涉及的图形是网格,erdos-reyni,barabasi-albert等等。
鉴于我的G.edges()
:
[(0, 1), (0, 10), (1, 11), (1, 2), (2, 3), (2, 12), ...]
我的weights
:
{(0,1):1.0, (0,10):1.0, (1,2):1.0, (1,11):1.0, (2,3):1.0, (2,12):1.0, ...}
如何为每条边分配相关权重?在这个简单的情况下,所有权重都是1.
我试图像这样直接将权重添加到G.edges()
for i, edge in enumerate(G.edges()):
G.edges[i]['weight']=weights[edge]
但是我收到了这个错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-48-6119dc6b7af0> in <module>()
10
11 for i, edge in enumerate(G.edges()):
---> 12 G.edges[i]['weight']=weights[edge]
TypeError: 'instancemethod' object has no attribute '__getitem__'
出了什么问题?由于G.edges()
是一个列表,为什么我不能像使用任何其他列表一样访问其元素?
答案 0 :(得分:5)
失败,因为edges
是一种方法。
documentation说这样做:
G[source][target]['weight'] = weight
例如,以下内容适用于我:
import networkx as nx
G = nx.Graph()
G.add_path([0, 1, 2, 3])
G[0][1]['weight'] = 3
>>> G.get_edge_data(0, 1)
{'weight': 3}
但是,您的代码类型确实失败了:
G.edges[0][1]['weight'] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-97b10ad2279a> in <module>()
----> 1 G.edges[0][1]['weight'] = 3
TypeError: 'instancemethod' object has no attribute '__getitem__'
在你的情况下,我建议
for e in G.edges():
G[e[0]][e[1]] = weights[e]
答案 1 :(得分:2)
添加这样的边:
g1.add_edge('Mark', 'Edward', weight = 3)
g1.add_edge('Joseph', 'Michael', weight = 3)
g1.add_edge('Joseph', 'Jason', weight = 4)
然后检查图形是否加权:
nx.is_weighted(g1)
是
按权重的大小对权重进行分类:
elarge = [(u, v) for (u, v, d) in g1.edges(data=True) if d['weight'] > 4]
esmall = [(u, v) for (u, v, d) in g1.edges(data=True) if d['weight'] <= 4]
下一步显示加权图:
pos = nx.spring_layout(g1) # positions for all nodes
nx.draw_networkx_nodes(g1, pos, node_size=100)
nx.draw_networkx_edges(g1, pos, edgelist=elarge,
width=5)
nx.draw_networkx_edges(g1, pos, edgelist=esmall,
width=5, alpha=0.5, edge_color='g', style='dashed')
答案 2 :(得分:0)
来自docs:
nx.set_edge_attributes(G, values = 1, name = 'weight')
weights
)相对应的键,
您可以使用nx.set_edge_attributes(G, values = weights, name = 'weight')
G.edges(data = True)