组合(加入)networkx图

ato*_*3ls 23 python graph-theory networkx

假设我有两个networkx图,G并且H:

G=nx.Graph()
fromnodes=[0,1,1,1,1,1,2]
tonodes=[1,2,3,4,5,6,7]
for x,y in zip(fromnodes,tonodes):
    G.add_edge(x,y)

H=nx.Graph()
fromnodes=range(2,8)
tonodes=range(8,14)
for x,y in zip(fromnodes,tonodes):
    H.add_edge(x,y)
Run Code Online (Sandbox Code Playgroud)

加入两个networkx图表的最佳方法是什么?

我想保留节点名称(注意公共节点,2到7).当我使用时nx.disjoint_union(G,H),这没有发生:

>>> G.nodes()
[0, 1, 2, 3, 4, 5, 6, 7]
>>> H.nodes()
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>> Un= nx.disjoint_union(G,H)
>>> Un.nodes()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# 
Run Code Online (Sandbox Code Playgroud)

H节点标签被改变(不是我想要的).我想在具有相同编号的节点处加入图形.

注意.这与NetworkX中的两个加权图组合并不重复.

Joe*_*oel 43

你正在寻找的功能是作曲.

import networkx as nx

G=nx.Graph()
G.add_node(1, weight = 2)
G.add_node(2, weight = 3)
G.add_edge(1,2, flux = 5)
G.add_edge(2,4)

H=nx.Graph()
H.add_node(1, weight = 4)
H.add_edge(1,2, flux = 10)
H.add_edge(1,3) 

F = nx.compose(G,H)
#F has all nodes & edges of both graphs, including attributes
#Where the attributes conflict, it uses the attributes of H.

G.nodes(data=True)
> NodeDataView({1: {'weight': 2}, 2: {'weight': 3}, 4: {}})
H.nodes(data=True)
> NodeDataView({1: {'weight': 4}, 2: {}, 3: {}})
F.nodes(data=True)
> NodeDataView({1: {'weight': 4}, 2: {'weight': 3}, 4: {}, 3: {}})

G.edges(data=True)
> EdgeDataView([(1, 2, {'flux': 5}), (2, 4, {})])
H.edges(data=True)
> EdgeDataView([(1, 2, {'flux': 10}), (1, 3, {})])
F.edges(data=True)
EdgeDataView([(1, 2, {'flux': 10}), (1, 3, {}), (2, 4, {})])
Run Code Online (Sandbox Code Playgroud)

还有其他选项来做对称差异,交集,......

如果你有多个图表连接在一起,你可以使用H,它只包含一个for循环compose_all.


ato*_*3ls 9

这样做了.

   U=nx.Graph()
   U.add_edges_from(G.edges()+H.edges())
   U.add_nodes_from(G.nodes()+H.nodes()) #deals with isolated nodes
Run Code Online (Sandbox Code Playgroud)

或者,保留边缘属性:

   U.add_edges_from(G.edges(data=True)+H.edges(data=True))
Run Code Online (Sandbox Code Playgroud)

并且,还要保留节点属性:

   U.add_nodes_from(G.nodes(data=True)+H.nodes(data=True))
Run Code Online (Sandbox Code Playgroud)