networkx 将加权有向图更改为无向图
networkx change weighted directed graph to undirected
networkx 中的内置函数是否可以将加权有向图更改为无向图?该功能应将两个有向边 (n1,n2,5) 和 (n2,n1,7) 更改为一个 (n1,n2,12)。
找了半天也没出钱。
Networkx 有一个 to_undirected 函数,但它不求和权重,它只是用原始图中最后找到的边权重更新权重:
If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the edges are encountered. For more customized control of the edge attributes use add_edge().
您应该像这样手动操作:
G = nx.DiGraph()
G.add_weighted_edges_from([
(1,2,3),
(1,3,4),
(2,1,5),
(2,3,1),
(3,2,2)
])
UG = G.to_undirected()
for node in G:
for ngbr in nx.neighbors(G, node):
if node in nx.neighbors(G, ngbr):
UG.edges[node, ngbr]['weight'] = (
G.edges[node, ngbr]['weight'] + G.edges[ngbr, node]['weight']
)
UG.edges.data('weight')
将return汇总权重:
EdgeDataView([(1, 2, 8), (1, 3, 4), (2, 3, 3)])
networkx 中的内置函数是否可以将加权有向图更改为无向图?该功能应将两个有向边 (n1,n2,5) 和 (n2,n1,7) 更改为一个 (n1,n2,12)。
找了半天也没出钱。
Networkx 有一个 to_undirected 函数,但它不求和权重,它只是用原始图中最后找到的边权重更新权重:
If edges in both directions (u, v) and (v, u) exist in the graph, attributes for the new undirected edge will be a combination of the attributes of the directed edges. The edge data is updated in the (arbitrary) order that the edges are encountered. For more customized control of the edge attributes use add_edge().
您应该像这样手动操作:
G = nx.DiGraph()
G.add_weighted_edges_from([
(1,2,3),
(1,3,4),
(2,1,5),
(2,3,1),
(3,2,2)
])
UG = G.to_undirected()
for node in G:
for ngbr in nx.neighbors(G, node):
if node in nx.neighbors(G, ngbr):
UG.edges[node, ngbr]['weight'] = (
G.edges[node, ngbr]['weight'] + G.edges[ngbr, node]['weight']
)
UG.edges.data('weight')
将return汇总权重:
EdgeDataView([(1, 2, 8), (1, 3, 4), (2, 3, 3)])